问题
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