看以下代码:
function NaiveDict(){}
NaiveDict.prototype.count=function(){
var i=0;
for(var name in this){
i++
//counts every property
}
return i
}
NaiveDict.prototype.toString=function(){
return "[objct NaiveDict]"
};
var dict=new NaiveDict();
dict.alice=34;
dict.bob=24;
dict.chris=64;
console.log(dict.count());
猜,会打印出几?
答案是:
5
The problem is that we are using the same object to store both the fixed properties of the NaiveDict data structure(count and toString) and the variable entries of the specific dictionary(alice,bob and chris).
不信的话,试试以下代码:
for(var name in dict){
console.log(name)
}
答案是:
alice
bob
chris
count
toString
也就是说要避免这种用法;