原型链继承
// 父 ==> 构造函数 function Person(name,age){ this.name = name this.age = age } Person.prototype.sayHello = function(){ console.log('谈话...') } // 子 ==> 构造函数 function Child(name,age){ this.name = name this.age = age } // 扭转Child 的原型对象,指向Person的公共属性,达到原型链的继承形式 Child.prototype = new Person() Child.prototype.constructor = Child let p = new.Child() p.sayHello() // '谈话...'
组合继承
// 父 ==> 构造函数 function Person(name,age){ this.name = name this.age = age } Person.prototype.sayHello = function(){ console.log('谈话...') } // 子 ==> 构造函数 function Child(name,age){ Person.call(this,name,age) // 继承Person的公有属性 } // 扭转Child 的原型对象,指向Person的公共属性,达到原型链的继承形式 Child.prototype = new Person() Child.prototype.constructor = Child let c = new.Child('wc',18) p.name // 'wc'
寄生组合继承
// 父 ==> 构造函数 function Person(name,age){ this.name = name this.age = age } Person.prototype.sayHello = function(){ console.log('谈话...') } // 子 ==> 构造函数 function Child(name,age){ Person.call(this,name,age) // 继承Person的公有属性 } // 创立一个空对象,将Person的原型的对象指向空对象,并将空对象的地址赋值给Child的原型对象 Child.prototype = Object.create(Person.prototype) Child.prototype.constructor = Child let c = new.Child('wc',18) p.name // 'wc'
Es6 class 继承
class Person{ constructor(name,age){ // 公有属性 this.name = name this.age = age } //sayHello 是共有属性 是原型链上的属性 sayHello(){ console.log('谈话...') } } //让 Child类 继承 Person类 class Child extends Person{ constructor(name,age){ super(name,age) // 调用父类的constrctor } } let c = new Child('wc',18) console.log(c.name) // 'wc' console.log(c.age) // 18 c.ayHello() // '谈话了'