Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

127
Views
How to access object's constructor in Javascript?

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
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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
);

about 4 years ago · Juan Pablo Isaza Report

0

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

Mozilla developer link

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!