0

我正在阅读另一个问题,我看到了这个:

var basketModule = (function() {
var basket = []; //private

return { //exposed to public
       addItem: function(values) {
            basket.push(values);
        },
        getItemCount: function() {
            return basket.length;
        },
        getTotal: function(){
            var q = this.getItemCount(),p=0;
            while(q--){
                p+= basket[q].price;
            }
        return p;
        }
      }
}());

你能解释一下他为什么把函数包装在( and )'s中吗?另外,这样做的目的是return什么?他就不能写字self.addItem = ...等等吗?

4

4 回答 4

2

当你用括号包装一个函数并添加()到它的末尾时,它是一个自执行函数。

(function() x() {
 //do something;
})();

而且,通过返回,他使basket变量变得有些私有。尝试basketModule.basket从其他任何地方获取,你会得到不确定的。

于 2012-04-28T11:25:16.057 回答
2

这就是所谓的 javascript模块模式。定义一个函数并立即调用它以防止变量在全局空间中或定义一个函数名。

于 2012-04-28T11:27:05.543 回答
0

The intention of the code is to create an object with three methods. addItem,getItemCount and getTotal. They all depend on state represented by basket.

if basket was defined globally that state would be exposed (and there could only ever be one variable basket. both of those can lead to issues so by wrapping the entire declaration the state is encapsulated and only accessible from the created object.

There are other ways of achieving the same and the pro's and con's are related to style and how many objects of that particular type you're going to need.

wrapping the function(){}() is required since function(){}() will not parse

于 2012-04-28T11:30:11.857 回答
0

注意最后一行的括号:(). 该函数已定义并立即调用: (function() { })();

return { ... }返回具有方法的对象addItem

于 2012-04-28T11:26:12.220 回答