【发布时间】:2015-03-29 09:05:15
【问题描述】:
function myclass(){
}
myclass.prototype = {
stuff: {},
getStuff: function(){
return Object.keys(this.stuff).length;
}
};
var m1 = new myclass();
m1.stuff[5] = 'test';
m1.stuff[6] = 'test';
var m2 = new myclass();
m2.stuff[12] = 'test';
m2.stuff[14] = 'test';
alert(m2.getStuff()); // 4 instead of 2 ?!
有人能解释一下为什么警报会打印 4 吗?
如果我创建了函数的新实例,则 stuff 属性应该为空。
【问题讨论】:
-
你可能想在构造函数中声明它,比如
this.stuff = {} -
原型是共享的,只有一个东西的实例,当变异时它会针对所有实例发生变化。这里详细解释:stackoverflow.com/a/16063711/1641941
标签: javascript node.js class object