Geo Mukkath
Geo Mukkath

Reputation: 145

How can I access a property of a constructor through an instance of that constructor?

Here the constructor is Animal. It has two instances duck and beagle. There is a function named eat() which is actually a prototype of Animal.

function Animal() {
  this.color = "brown";
 }

Animal.prototype = {
  constructor: Animal,
  eat: function() {
    console.log("nom nom nom");
  }
};

let duck = Object.create(Animal.prototype); 
let beagle = Object.create(Animal.prototype); 
duck.eat();
console.log(duck.color);

here

duck.eat() 

works, but duck must also inherit the color brown right ? Why am I not able to access it using

duck.color ?

Upvotes: 0

Views: 36

Answers (2)

vipul patel
vipul patel

Reputation: 736

No It wont inherit,

Please read the definition of Object.create.

"The Object.create() method creates a new object, using an existing object as the prototype of the newly created object"

Means, only prototype will be copied from existing object on will be placed in newly create object's prototype

Here color is instance variable not prototype. Hence wont be available in newly created duck object.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create

Upvotes: 0

Quentin
Quentin

Reputation: 943211

There is no color property on Animal.prototype. It is dynamically added to the object when the constructor function is called… but you aren't calling the constructor function at all.

If you want to create an instance of a class, then call the constructor function. Don't use Object.create.

function Animal() {
  this.color = "brown";
 }

Animal.prototype = {
  eat: function() {
    console.log("nom nom nom");
  }
};

let duck = new Animal();
let beagle = new Animal();
duck.eat();
console.log(duck.color);

Upvotes: 3

Related Questions