原型和 __proto__ 令人困惑的结果

prototype and __proto__ confusing result

var Person = function () { this.bar = 'bar' };
Person.prototype.foo = 'foo'; //proto as property


var Chef = function () { this.goo = 'goo' };
Chef.prototype = new Person();



var cody = function () { this.goo = 'goo' };
cody.prototype = new Chef();

var a = new cody();

对 JavaScript 原型非常困惑

a.__proto__   why is it Chef{goo:"goo"} and not cody{}
a.constructor.prototype why is it Person {foo: "foo"} and not Chef{goo:"goo"}
a.constructor  why is it function Person() and not function cody()

有人可以解释这些问题并建议 link 研究 JavaScript 中的多级继承吗?

让我们再好好看看你的代码:

//OK, so this is just a regular constructor that sets bar in the constructor and foo on the prototype.
var Person = function () { this.bar = 'bar' };
Person.prototype.foo = 'foo';

//This is a constructor Chef that inherits from Person. It also sets goo in the constructor.
var Chef = function () { this.goo = 'goo' };
//However, it inherits from Person in an odd way: It calls an instantiation of Person and set the prototype to that.
//This sets Chef.prototype.constructor to Person because it's an instance of Person, so all instances of Chef will have the .constructor property of Person.
//It also sets all instances of Chef's __proto__ to Person.prototype since the Chef.prototype directly comes from Person.
Chef.prototype = new Person();

//Now, this is a constructor that inherits from Chef and sets goo in the constructor.
var cody = function () { this.goo = 'goo' };
//However, it does inheritance in the same weird way: By making an instatiation of Chef and setting the prototype to that.
//This makes cody.prototype.constructor the same as Chef.prototype.constructor, which is Person. Thus, cody.prototype.constructor is Person.
//However, code.prototype directly inherits from Chef because it's an instance from Chef. This means that all instances of cody will have the __proto__ from Chef, not from Person and not from cody.
cody.prototype = new Chef();

//Thus, following our analysis, we have the following info on a:
//a.__proto__ is Chef.prototype because cody.prototype is an instance of Chef. This means a.__proto__ is Chef{goo:"goo"},
//a.constructor is Person because cody.prototype.constructor is Chef.prototype.constructor which is Person.prototype.constructor which is just Person.
//Since a.constructor is Person, a.constructor.prototype is Person.prototype and thus Person {foo:"foo"}.
var a = new cody();

希望通过对您代码的分析,帮助您更好地理解 JavaScript 的原型系统!为了更好地实现 JavaScript 继承,我推荐 Khan Academy.