Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

121
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

0

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

Mozilla developer link

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda