组合继承就是使用原型链继承原型上的属性和方法,通过盗用构造函数继承实例的属性。这样做的好处是既可以把方法定义在原型上实现重用,又可以让每个实例拥有自己的属性
实现代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| function Parent(name, age) { this.name = name this.age = age this.house = 150 } Parent.prototype.sayHi = () => { console.log('hello world !') }
function Children(name, age) { Parent.call(this, name, age) } Children.prototype = Object.create(Parent.prototype)
Children.prototype.constructor = Children
let xiaowei = new Children('小维', 18)
console.log(xiaowei) xiaowei.sayHi() console.log(xiaowei instanceof Children) console.log(xiaowei instanceof Parent)
|