Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the constructor changed?

Why does the constructor change from Foo to Object after adding a prototype? How can I get access to the original constructor?

Code:

function Foo() {}
var foo1 = new Foo();
console.log('foo1: ' + foo1.constructor);

Foo.prototype = {}
var foo2 = new Foo();
console.log('foo2: ' + foo2.constructor);

Output:

foo1: function Foo() {}

foo2: function Object() {
    [native code]
}

http://jsfiddle.net/vDCTJ/

like image 285
Stas Jaro Avatar asked Feb 16 '23 09:02

Stas Jaro


1 Answers

It happens because you gave Foo a brand new object for its prototype, and you didn't set that object's "constructor" property.

Foo.prototype = { constructor: Foo };

Instantiated function objects get an object for their "prototype" property that's already initialized that way.

like image 176
Pointy Avatar answered Feb 18 '23 22:02

Pointy