我正在阅读 javascript 设计模式书,并在阅读“命令模式”时遇到了下面的代码。我一直在试图理解为什么这段代码被包裹在一个立即被调用的匿名函数上,特别是因为没有其他私有变量可以被关闭。这与仅将 CarManager 声明为对象文字有何不同?
(function(){
var CarManager = {
// request information
requestInfo: function( model, id ){
return 'The information for ' + model + ' with ID ' + id + ' is foobar';
},
// purchase the car
buyVehicle: function( model, id ){
return 'You have successfully purchased Item ' + id + ', a ' + model;
},
// arrange a viewing
arrangeViewing: function( model, id ){
return 'You have successfully booked a viewing of ' + model + ' ( ' + id + ' ) ';
}
};
})();