1

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/

Aadit M Shah
  • 72,912
  • 30
  • 168
  • 299
mw1
  • 1,482
  • 1
  • 11
  • 18

2 Answers2

6

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/

Community
  • 1
  • 1
Aadit M Shah
  • 72,912
  • 30
  • 168
  • 299
  • Just tried it out, but getting the same behavior as in my original post. Here is the fiddle with your changes: http://jsfiddle.net/hammerbrostime/GMFLv/ – mw1 Jun 19 '13 at 14:29
  • @hammerbrostime - You're doing it wrong. Changing the `constructor` property doesn't change the constructor. Do this instead: http://jsfiddle.net/GMFLv/1/ – Aadit M Shah Jun 19 '13 at 14:33
  • Aadit, thanks for the detailed response. Is it necessary to create a new object? I'd like to see if we can change the constructor for the original constructorQuestion object, so that we could call new constructorQuestion(). – mw1 Jun 19 '13 at 14:47
  • @hammerbrostime - No, this is the only way to achieve what you're trying to achieve. – Aadit M Shah Jun 20 '13 at 02:01
1

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;
karaxuna
  • 26,752
  • 13
  • 82
  • 117