Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the constructor not the constructing function?

Tags:

javascript

Consider the following snippet:

​f = function() {};
f.prototype = {};
thing = new f;

I was surprised to see that thing.constructor​ is Object(). (See fiddle here.)

Why isn't thing.constructor the function f? ​

like image 702
Randomblue Avatar asked Sep 12 '12 19:09

Randomblue


1 Answers

Because you've entirely replaced the original prototype object of f with a plain object. It was the original prototype object that held the reference to f via the .constructor property.

The constructor of an object created using object literal syntax will be the Object constructor.

To get it back, you'd need to put it there manually.

f = function() {};
f.prototype = {};
f.prototype.constructor = f;
thing = new f;

This will shadow the .constructor property on in the prototype chain of the new prototype object.

If you delete that property, you'll get Object again.

delete f.prototype.constructor;

console.log(thing.constructor); // Object
like image 69
gray state is coming Avatar answered Sep 27 '22 21:09

gray state is coming