0

我正在尝试创建类似于静态语言“静态字段”的东西。基本上:计数器属性应该在每次调用 init 函数时递增,但不管在哪个实例上。这是我用来测试的示例代码(http://jsfiddle.net/HK8BY/2/):

var Widget = {
    counter: 0,
    init: function () {
        this.counter++;
        console.log("init called: " + this.counter);
    }
};

var t1 = Object.create(Widget);
var t2 = Object.create(Widget);
t1.init(); // should print: init called 1
t2.init(); // should print: init called 2
console.log(t1);
console.log(t2);

目前,当我 console.log 实例时,我看到proto和 instance 都包含 counter 属性。我认为通过这种方法,只有proto才能拥有它。

那么如何将其更改为原型中只有计数器?

4

3 回答 3

2
var twitter = (function() {
    var counter = 0;
    return {
        init : function() { counter++; console.log("init called: " + counter); }
    };
}()); 

var t1 = Object.create(twitter);
var t2 = Object.create(twitter);

t1.init();
t2.init();

http://jsfiddle.net/HK8BY/1/

因此,您只需创建返回所需对象的 IEFE(立即执行函数表达式)。该counter变量可用于该对象init函数的闭包。

于 2013-01-20T12:15:25.993 回答
0
var Widget = {
    init: function () {
        this.prototype.counter++;
        console.log("init called: " + this.counter);
    }
};
Widget.prototype.counter = 0;

var t1 = Object.create(Widget);
var t2 = Object.create(Widget);
t1.init();
t2.init();
console.log(t1);
console.log(t2);
于 2013-01-20T12:17:42.010 回答
0

You can simulate static fields by defining properties on a constructor function, but if you prefer to use Object.create in place of new then this might not be a solution you want to consider.

function Widget() {
    this.init()
};

Widget.counter = 0;

Widget.prototype.init = function() {
    this.constructor.counter++;
    console.log("init called: " + this.constructor.counter);
};
于 2013-01-21T11:46:07.527 回答