ES5与ES6继承code
文章目录
ES5 继承
1.利用原型链继承
将要继承的对象,赋值给构造器的对象原型
var Obj1 = function(){
this.name = 'Obj1Name'
}
var Obj2 = function()
this.age = 21
}
Obj2.prototype = new Obj1()
var instance1 = new Obj2()
console.log(instance1.name) \\ Obj1Name
console.log(instance1) \\{age:21, _proto_: Obj1}2.构造器继承
通过调用父类构造器 通过this,将父类的属性添加给自己(子类对象),没有改变对象原型
var Obj3 = function(){
this.name = 'Obj3Name'
}
var Obj4 = function(){
this.age = 22
Obj3.call(this)
}
var instance2 = new Obj4()
console.log(instance2.name) // Obj3Name
console.log(instance2) //{name:'Obj3Name', age: 22}3.原型式继承
通过继承对象原型, 原理也是原型链继承
var person = {
name: 'wdm'
}
var student = Object.create(person)
console.log(student.name) // wdm
console.log(student) //{_proto_: person}组合继承
将原型链继承与构造器继承结合,使用原型链继承方法,构造器继承属性。
function Animal(){
this.property = 'animal'
}
Animal.prototype.eat = function(){
return '吃了一个苹果'
}
function Cat(){
Animal.call(this)
this.weight = '30kg'
}
Cat.prototype = new Animal()
Cat.prototype.constructor = Cat
var cat1 = new Cat()
console.log(cat1.property)
console.log(cat1.eat())封装组合继承
组合继承的升级,将新建一个类,代替父类,去掉父类的实例。为子类原型对象赋父类实例时,减免父类的属性初始化。
function Person(){
this.age = 21
}
Person.prototype.sayHi = function(){
return 'hi'
}
function Student(){
Person.call(this)
this.name = 'wdm'
}
function Super(){
}
Super.prototype = Person.prototype
Student.prototype = new Super()
Student.prototype.constructor = Student
var s1 = new Student()
console.log(s1.name)
console.log(s1.age)
console.log(s1.sayHi())ES6 继承
ES6的特性,通过extends继承,super()调用父类构造器,返回父类this。
class father {
constructor(){
}
sayhi(){
console.log('ES6 HI')
}
}
class son extends father{
constructor(){
super() //调用父类构造器,返回父类this
}
sayhi(){
return super.sayhi() //super返回父类this
}
}
var instance3 = new son()
console.log(instance3) //{_proto_: father}
instance3.sayhi() // ES6 HI
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论