简体   繁体   English

__proto__ 和 JavaScript 中的继承

[英]__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.这几天我一直在研究 JavaScript 继承,虽然我已经取得了很大的进步,但有些事情我还不是很明白。

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. m__proto__属性指向一个不是Manager当前原型的对象。 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摘自JavaScript:权威指南,第 5 版,作者: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 */

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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