许多的js包中,都有这样的一种结构:
(function() {
var box = function() {
var width = 1,
height = 1;
// For each small multiple…
function box(g) {
// your code;
}
box.width = function(x) {
if (!arguments.length)
return width;
width = x;
return box;
};
box.height = function(x) {
if (!arguments.length)
return height;
height = x;
return box;
};
return box;
};
})();
好像是一种传统,从github上面找到的开源代码里面,都是这种结构。让我们来花几分钟的时间,解读一下。
(function() {
// you code here
})();
上面代码的含义是:创建一个匿名函数,并且执行这个函数。所以,在一个js文档中,如果看到了,这段代码,直接忽略为执行里面的代码就得了。
关键是下面的几行代码:
var box = function() {
var width = 1,
height = 1,
// For each small multiple…
function box(g) {
// your code;
}
box.width = function(x) {
...
};
box.height = function(x) {
...
};
return box;
};
在函数box里面,又定义了一个函数对象box (第6行),这个对象函数还有属性:width和height,为什么要这样?
目的是为了在调用外面的box(第1行)的时候,返回的是里面的box函数(第6行),直接调用里面的box。如下:
var chart = box()
.width(width)
.height(height);
在调用box()的时候返回里面的box函数对象,后执行里面box函数的width函数和height函数。
这是一种习惯,可以将一个对象中的数据,以另外一种方式呈现在调用它的上下文中。仅此而已。