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()
有人可以解释一下这些问题,并建议在JavaScript中学习多级继承的链接吗?
答案 0 :(得分:0)
让我们再看看你的代码:
//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。