JavaScript Inheritance: When are my Derived Members?

Take a look at the following code:

function Primate() { this.prototype = Object; this.prototype.hairy = true; } function Human() { this.prototype = Primate; } new Human(); 

When you check new Human() , there is no hairy element. I would expect that there will be one. Is there any other way that I should inherit from Primate ? Something involving Object.create() (ECMAScript5 great for use in my script)?

+6
source share
1 answer

When your code is written, objects created using new Human() will have the prototype property, the value of which is a reference to the Primate function. This is clearly not what you want (and it is not particularly special).

Few things:

  • Usually you want to change the prototype function that is intended to be used as a constructor (with the new operator). In other words, you want to set prototype to Human (not to an instance of Human ).

  • The value you assign to prototype should be an instance of the desired type (or, if you do not need to initialize, the desired prototype type), and not a reference to its constructor.

  • There is no need to explicitly assign Object (or Object instances) to the prototype function. This is implicit.

You probably want something like this:

 function Primate() { this.hairy = true; } function Human() {} Human.prototype = new Primate(); Human.prototype.constructor = Human; var h = new Human(); 

Human > has a hairy property whose value is true.

In the previous example, hairy assigned its value only once when Primate is called, so a Primate Human.prototype must be assigned to Human.prototype . Instead, it could be written so that such initialization is not required.

Example:

 function Primate() {} Primate.prototype.hairy = true; function Human() {} Human.prototype = Primate.prototype; Human.prototype.constructor = Human; var h = new Human(); 
+4
source

Source: https://habr.com/ru/post/907253/


All Articles