function Father(money, house, car, huabei) {
this.money = money
this.house = house
this.car = car
this.huabei = huabei
}
``
Father.prototype.sayHi = function () {
console.log(this)
}
function Child(money, house, car, huabei, gf) {
// 属性继承
Father.apply(this, [ money, house, car, huabei ])
this.gf = gf
}
方法一:
// 这种方式缺点:会污染父构造函数的prototype属性
Child.prototype = Father.prototype
Child.prototype.kiss = function () {
code....}
方法二:
// 这种方式缺点:语义不明,因为Father很有可能有参数,而此时传参不语义,我们的目的只想要一个原型链的继承,而没有实际的对象实例
Child.prototype = new Father()
方法三:
Child.prototype.__proto__ = Father.prototype
--------最佳的实现方式
// 前置知识:var obj2 = Object.create(obj1)
// 创建一个对象 obj2,让 obj2.__proto__ 指向 obj1
// 缺点:Object.create 兼容有点小问题,不支持的时候需要自己实现
Child.prototype = Object.create(Father.prototype)
Child.prototype.constructor = Child
为什么Child.prototype = Object.create(Father.prototype)
Child.prototype.constructor = Child的继承方式是相对最优的,而非Child.prototype.__proto__ = Father.prototype
Child.prototype.__proto__ = Father.prototype
我理解你是想说实例上的原型等价于要继承的原型
Object.create()