var Gadget = function () {
// static variable/property
var counter = 0;
// returning the new implementation
// of the constructor
return function () {
console.log(counter += 1);
};
}(); // execute immediately
var g1 = new Gadget(); // logs 1
var g2 = new Gadget(); // logs 2
var g3 = new Gadget(); // logs 3
我调试这段代码,var counter = 0;
期间不会执行new Gadget()
,输出是1,2,3
。
var Gadget = function () {
// static variable/property
var counter = 0;
// returning the new implementation
// of the constructor
return function () {
console.log(counter += 1);
}();
}; // execute immediately
var g1 = new Gadget(); // logs 1
var g2 = new Gadget(); // logs 2
var g3 = new Gadget(); // logs 3
我调试这段代码var counter = 0;
将在 期间执行new Gadget()
,输出为1,1,1
.
此演示代码采用 javascript 模式,私有静态成员。我很难理解这一点。