How to change the constructor of an object?

坚强是说给别人听的谎言 提交于 2019-12-11 12:48:30

问题


I am diving deeper into Javascript, and learning how constructor methods work.

In the code below, I would expect that I would be able to overwrite the constructor of an object, so that newly created instances would use the new constructor. However, I can't seem to make new instances use a new constructor.

Any insight as to what is going on would be greatly appreciated!

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

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

Here's the fiddle: http://jsfiddle.net/hammerbrostime/6nxSW/1/


回答1:


The constructor is a property of the prototype of the function, not the function itself. Do:

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

For more information see: https://stackoverflow.com/a/8096017/783743


BTW, if you expect the code howComeConstructorHasNotChanged = new constructorQuestion(); to alert "new constructor" that won't happen. This is because you're not calling the new constructor, you're calling the old one. What you want is:

howComeConstructorHasNotChanged = new constructorQuestion.prototype.constructor;

Changing the constructor property doesn't magically change the constructor.

What you really want is:

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

c = new constructorQuestion();

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

newConstructor.prototype = constructorQuestion.prototype;

howComeConstructorHasNotChanged = new newConstructor();

This will work. See: http://jsfiddle.net/GMFLv/1/




回答2:


I think it will be same to create new object with same prototype like this:

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

newClass.prototype = constructorQuestion.prototype;


来源:https://stackoverflow.com/questions/17193861/how-to-change-the-constructor-of-an-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!