简体   繁体   中英

__proto__ and inheritance in JavaScript

I've been studying JavaScript inheritance for a couple of days, and although I've made quite a lot of progress there are some things I don't quite understand yet.

For example, I find this behaviour 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 's __proto__ property points to an object which is not Manager 's current prototype. This is a little counterintuitive, given that:

An object inherits properties even if they are added to its prototype after the object is created.

Taken from JavaScript: The Definitive Guide, 5th Edition, By David Flanagan

Couldn't this behaviour be applied to the aforementioned case, too?

Can anyone clarify?

It's a little confusing because functions are themselves 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 */

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM