【发布时间】:2012-11-09 07:15:39
【问题描述】:
我一直在尝试在 javascript 中模拟静态属性。 在几个地方已经提到,class.prototype.property 在从该类继承的所有对象中都是静态的。但我的 POC 另有说法。请看:
使用 Class.prototype.property
//Employee class
function Employee() {
this.getCount = function(){
return this.count;
};
this.count += 1;
}
Employee.prototype.count = 3;
var emp = [], i;
for (i = 0; i < 3; i++) {
emp[i] = new Employee();
console.log("employee count is "+ emp[i].getCount());
}
/*Output is:
employee count is 4
employee count is 4
employee count is 4*/
我的问题 #1:如果这是静态的,那么 count 的值不应该是 4、5、6 等,因为所有对象共享相同的 count 变量吗?
然后我用 Class.prototype 做了另一个 POC,我认为这是静态的。
使用 Class.property
//Employee class
function Employee() {
this.getCount = function(){
return Employee.count;
};
Employee.count++;
}
Employee.count = 3;
var emp = [], i;
for (i = 0; i < 3; i++) {
emp[i] = new Employee();
console.log("employee count is "+ emp[i].getCount());
}
/*Output is:
employee count is 4
employee count is 5
employee count is 6*/
我的问题 #2:我没有看到直接使用 class.property。记住我上面的代码,javascript中的静态变量究竟是如何制作的?
或者我在这里写错了什么?这不是正确的认识吗?
【问题讨论】:
-
我一直使用第二种形式。
-
我认为
this始终是一个 instance 指向 determine-by-run-time 对象,而Employee在您的代码中是一个“原型声明”。
标签: javascript static prototype