2013-07-23 57 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