__proto__ and inheritance in Javascript

I studied javascript inheritance for a couple of days, and although I have made quite a bit of progress, there are some things that I do not quite understand yet.

For example, I find this behavior quite confusing:

var Employee = function Employee() { this.company = 'xyz'; }; var Manager = function Manager() { this.wage = 'high'; }; var m = new Manager(); m; // { "wage": "high", __proto__ : Manager } -- no problems so far. Manager.prototype = new Employee(); var n = new Manager; m.company; // undefined n.company; // "xyz" 

m __proto__ property points to an object that is not a prototype of Manager . This is a little illogical, given that:

An object inherits properties, even if they are added to its prototype after creating the object.

Adapted from JavaScript: The Final Guide, Fifth Edition, David Flanagan

Is it possible to apply this behavior to the above case?

Can anyone clarify?

+6
javascript inheritance prototype
source share
1 answer

This is a bit confusing because the functions themselves are objects:

 function Employee() {this.company = 'xyz';} function Manager() {} var m = new Manager(); Manager.prototype = new Employee(); /* You set the prototype on the Manager function (object), your m instance and Manager function are separate objects. At this point the prototype of m is still undefined */ m = new Manager(); m.company; // 'xyz' /* Creating a new Manager copies the new prototype */ 
+4
source share

All Articles