2013-07-23 113 views
1

我有这样的代码:扩展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/

+0

以这种方式设置原型(您的第一个示例'pPoint.prototype = {}')将使pPoint.prototype.constructor指向Object而不是pPoint。构造函数应指向正确的功能,如果你不使用它,并且你不希望其他人扩展你的代码,这应该不是一个问题,但它是值得一提的。 – HMR

回答

5

Array.prototype属性不可写。因此,Array.prototype = ...不起作用。

你可以看Object.getOwnPropertyDescriptor(Array, 'prototype').writable,这是false


假若你是能够做到这一点,你会失去所有的内置阵列的方法,因为它们是你想用来替换和新对象的标准Array.prototype的性质没有。

+0

哦有趣。所以通过这样做,我将有效地重写使用“原型”设置的任何内容。谢谢! :) – PCoelho

+0

那么,你可能只会释放在赋值后创建的*数组实例的方法。但这是无稽之谈,因为无论如何都无法完成。 : - / – RobG