effective javascript(-)

来源:互联网 发布:单片机报警器汇编程序 编辑:程序博客网 时间:2024/05/21 11:46

看以下代码:

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)}

答案是:

alicebobchriscounttoString

也就是说要避免这种用法;

原创粉丝点击