Home > Net >  How to access object's constructor in Javascript?
How to access object's constructor in Javascript?

Time:03-07

I have this piece of code:

var MyConstructor = function(){};
var MyObject = new MyConstructor();

What I noticed is MyObject.constructor is not pointing to MyConstructor. So what is the standard way of accessing the constructor of an object from the object itself?

I need this to access constructor's prototype properties like MyConstructor.prototype = {mykey : "value"}. I can access mykey this way: MyConstructor.prototype.mykey but MyObject.constructor.prototype.mykey is not defined.

Here is the complete code and their output using jsconsole.com:

var MyConstructor = function(){};
MyConstructor.prototype = {mykey : "value"};
var MyObject = new MyConstructor();

MyObject.mykey; // output: "value"
MyConstructor.prototype.mykey; // output: "value"
MyObject.constructor.prototype.mykey; // output: undefined
MyObject.constructor === MyConstructor; // output: false
MyObject.constructor.prototype.mykey === "value";  // output: false

CodePudding user response:

This happens because you change the prototype property of MyConstructor. That means that MyObject is created from that object and does not get the constructor property that the original prototype object had. So in your test case, MyObject.constructor === Object, since that is the constructor that is used for the object literal {mykey: "value"}.

To avoid this behaviour, don't assign a new object to the prototype property, but mutate the existing one:

var MyConstructor = function(){};
MyConstructor.prototype.mykey = "value";
var MyObject = new MyConstructor();

console.log(
  MyObject.mykey, // output: "value"
  MyConstructor.prototype.mykey, // output: "value"
  MyObject.constructor.prototype.mykey, // output: "value"
  MyObject.constructor === MyConstructor, // output: true
  MyObject.constructor.prototype.mykey === "value",  // output: true
);

CodePudding user response:

Object.getPrototypeOf(MyObject).mykey gets the prototype directly from MyObject.

Mozilla developer link

  • Related