PCo*_*lho 1 javascript prototype class
我有这个代码:
pPoint = function(x,y){
this.x = x || 0;
this.y = y || 0;
}
pPoint.prototype = {
constructor:pPoint,
add:function(){
return this.x+this.y;
}
}
Run Code Online (Sandbox Code Playgroud)
如果我这样做:
a = new pPoint(10,20)
console.log(a.add());
Run Code Online (Sandbox Code Playgroud)
按预期工作(返回30).
但是,如果我这样做:
Array.prototype = {
abcd:function(){
console.log("bla bla testing");
}
}
Run Code Online (Sandbox Code Playgroud)
然后这样做:
b = new Array();
b.abcd();
Run Code Online (Sandbox Code Playgroud)
它不起作用......为什么?
我知道如果我这样做很好......
Array.prototype.abcd:function(){
console.log("bla bla testing");
}
}
Run Code Online (Sandbox Code Playgroud)
我只是不明白为什么preivous的工作在我的pPoint而不是在Array ...
该Array.prototype物业不可写.
因此,Array.prototype = ...没有效果.
您可以通过查看来看到这Object.getOwnPropertyDescriptor(Array, 'prototype').writable一点false.
如果你能够做到这一点,你将失去所有的内置数组方法,因为它们是标准的属性,Array.prototype而不是你试图用它替换它的新对象.
| 归档时间: |
|
| 查看次数: |
66 次 |
| 最近记录: |