Reputation: 2764
This question is purely of academic value.
Given a constructor function Foo()
:
function Foo(){
this.x = 1;
}
and an instance of that class:
var o = new Foo(); // Instance of Foo()
console.log(o.constructor); // => Foo(): The constructor of `o` is `Foo()` - this makes sense so far.
But, if I set the prototype property of Foo()
constructor manually...
Foo.prototype = { z: 3};
var o = new Foo(); // Instance of Foo()
o
's constructor becomes Object()
, so not Foo()
:
console.log(o.constructor); // => Object {}
I get that Foo()
(o's constructor's prototype
property) is changed, but isn't the constructor of an instance of Foo()
still Foo()
? Isn't it the prototype
property of Foo() that is changed, not Foo() itself?
Upvotes: 0
Views: 71
Reputation: 382122
A constructor is nothing else than a simple function. Any function is a constructor.
The real and sole magic is in the new operator : it's that operator which creates a new instance of the given "class".
Quoting the MDN :
When the code new foo(...) is executed, the following things happen:
A new object is created, inheriting from foo.prototype.
The constructor function foo is called with the specified arguments and this bound to the newly created object. new foo is equivalent to new foo(), i.e. if no argument list is specified, foo is called without arguments.
The object returned by the constructor function becomes the result of the whole new expression. If the constructor function doesn't explicitly return an object, the object created in step 1 is used instead. (Normally constructors don't return a value, but they can choose to do so if they want to override the normal object creation process.)
Note the order : you don't apply new
to Foo()
but to Foo
. That's why you can also write
var o = new Foo;
Upvotes: 2