我有这样的代码:扩展JavaScript的原生对象
pPoint = function(x,y){
this.x = x || 0;
this.y = y || 0;
}
pPoint.prototype = {
constructor:pPoint,
add:function(){
return this.x+this.y;
}
}
如果我做的:
a = new pPoint(10,20)
console.log(a.add());
按预期工作(返回30)。
但是,如果我这样做:
Array.prototype = {
abcd:function(){
console.log("bla bla testing");
}
}
然后做到这一点:
b = new Array();
b.abcd();
它不工作,为什么?
我知道,如果我做这工作得很好...
Array.prototype.abcd:function(){
console.log("bla bla testing");
}
}
我只是不明白为什么preivous一个工作在我的pPoint而不是在阵列...
小提琴:http://jsfiddle.net/paulocoelho/wBzhk/
以这种方式设置原型(您的第一个示例'pPoint.prototype = {}')将使pPoint.prototype.constructor指向Object而不是pPoint。构造函数应指向正确的功能,如果你不使用它,并且你不希望其他人扩展你的代码,这应该不是一个问题,但它是值得一提的。 – HMR