2013-06-19 32 views
1

我潛水深入到JavaScript和學習構造函數方法是如何工作的。如何更改對象的構造函數?

在下面的代碼,我希望,我將能夠覆蓋一個對象的構造函數,使新創建的實例將使用新的構造函數。但是,我似乎無法讓新實例使用新的構造函數。

任何有識之士爲正在發生的事情,將不勝感激!

function constructorQuestion() { 
    alert("this is the original constructor"); 
}; 

c = new constructorQuestion(); 
constructorQuestion.constructor = function() { alert("new constructor");} 
howComeConstructorHasNotChanged = new constructorQuestion(); 

這裏的小提琴:http://jsfiddle.net/hammerbrostime/6nxSW/1/

+0

忘了加上小提琴:http://jsfiddle.net/hammerbrostime/6nxSW/1/ – hammerbrostime

回答

6

constructor是功能,而不是函數本身的prototype的屬性。不要:

constructorQuestion.prototype.constructor = function() { 
    alert("new constructor"); 
} 

欲瞭解更多信息,請參閱:https://stackoverflow.com/a/8096017/783743


順便說一句,如果你期望的代碼howComeConstructorHasNotChanged = new constructorQuestion();提醒"new constructor"不會發生的。這是因爲你沒有調用新的構造函數,而是在調用舊的構造函數。你想要的是:

howComeConstructorHasNotChanged = new constructorQuestion.prototype.constructor; 

更改constructor屬性不會幻化構造。

你真正想要的是:

function constructorQuestion() { 
    alert("this is the original constructor"); 
}; 

c = new constructorQuestion(); 

function newConstructor() { 
    alert("new constructor"); 
} 

newConstructor.prototype = constructorQuestion.prototype; 

howComeConstructorHasNotChanged = new newConstructor(); 

這將工作。請參閱:http://jsfiddle.net/GMFLv/1/

+0

只是試了一下,但得到了與我原來的帖子相同的行爲。這裏是你的改動小提琴:http://jsfiddle.net/hammerbrostime/GMFLv/ – hammerbrostime

+0

@hammerbrostime - 你就錯了。改變'constructor'屬性不會改變構造函數。做到這一點,而不是:http://jsfiddle.net/GMFLv/1/ –

+0

Aadit,感謝您的詳細答覆。是否有必要創建一個新的對象?我想看看我們是否可以改變原始constructorQuestion對象的構造函數,以便我們可以調用新的constructorQuestion()。 – hammerbrostime

1

我認爲這將是相同的,以創建具有相同的原型喜歡這個新對象:

function newClass(){ 
    alert('new class with same prototype'); 
} 

newClass.prototype = constructorQuestion.prototype;