1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | function PeopleNew (name, sex, age) { this .name = name this .sex = sex this .age = age } PeopleNew.prototype.info = function () { console.log(`${ this .name},性别:${ this .sex},现年${ this .age}`) } function ChinesePeopleNew (name, sex, age, national) { PeopleNew.call( this , name, sex, age) this .national = national } ChinesePeopleNew.prototype.getHuKou = function () { console.log( 'getHuKou' ) } function __extends (son, parent) { function MiddleNew () { this .constructor = son } MiddleNew.prototype = parent.prototype return new MiddleNew() } ChinesePeopleNew.prototype = __extends(ChinesePeopleNew, PeopleNew) |
上面的代码是最开始实现寄生组合式的代码,也是改变了子构造函数的原型对象空间指向,导致其方法失效
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | function PeopleNew (name, sex, age) { this .name = name this .sex = sex this .age = age } PeopleNew.prototype.info = function () { console.log(`${ this .name},性别:${ this .sex},现年${ this .age}`) } function ChinesePeopleNew (name, sex, age, national) { PeopleNew.call( this , name, sex, age) this .national = national } ChinesePeopleNew.prototype.getHuKou = function () { console.log( 'getHuKou' ) } function __extends (son, parent) { function MiddleNew () { this .constructor = son } MiddleNew.prototype = son.prototype MiddleNew.prototype.__proto__ = parent.prototype return new MiddleNew() } ChinesePeopleNew.prototype = __extends(ChinesePeopleNew, PeopleNew) |
其实稍加改动之后,也可以满足在原型对象空间上如果找不到该方法,就可以在原型对象空间的原型对象空间中找到该方法,实现继承的效果
那是不是说,其实每种方法都一样可以解决这个问题
那么是不是说其实只要子构造函数的原型链存在某一个构造函数的方法,就是继承了这个构造函数,也就是可以解释成和用什么方法加上去的无关