es6类 class

es5的类的继承

存在问题 Person1 执行了两次,造成了多构造一次的性能开销

组合继承

function Person(name, age) {
    this.name = name
    this.age = age

    this.say = function () { //this不能少
        console.log(this.name, this.age)
    }
}
Person.prototype.eat = function () {
    console.log("hello")
}

function Person1(name, age, sex) {
    //this指向其实例化对象
    Person.call(this, name, age) //参数一个都不能少
    this.name = name
    this.age = age
    this.sex = sex
}

Person1.prototype = new Person(); // Person1.prototype原型对象被重置 Parent.prototype 也可以实现
Person1.prototype.constructor = Person1 || Person.prototype
    ; //再次指回原来的实例方法

Person1.prototype.run = function () {
    console.log(this.name, this.age, this.sex)
}
var p1 = new Person("李白", 15)
var p2 = new Person1("李白", 15, "男")

p1.eat() //hello
p2.run() //李白 15 男
p2.eat() //hello
p2.say() //李白 15

寄生组合式继承

function Parent(name, age) {
    this.name = name,
        this.age = age
}

Parent.prototype.Say = function () {
    console.log(this.name);
}

function Children(name, age,sex) {
    Parent.call(this, name, age)	// 1
    this.sex=sex
}

// 2
Children.prototype = Object.create(Parent.prototype);	// 这就是不同
// 3
Children.prototype.constructor = Children;


let p1 = new Children("小王", 18,"man")
console.log(p1);    // Children { name: '小王', age: 18, sex: 'man' }
p1.Say()

ES6中的类的继承

实际也是使用寄生组合式继承来实现的
子类必须在constructor方法中调用super方法,否则新建实例时会报错。这是因为子类没有自己的this对象,而是继承父类的this对象,然后对其进行加工。如果不调用super方法,子类就得不到this对象。

class Father {
    constructor(x, y) {
        this.x = x
        this.y = y
    }

    sum() {
        console.log(this.x + this.y)
    }
}

class son extends Father { //继承父类
    constructor(x, y,z) {    //不能用this  
        super(x, y) //调用父类的构造函数,通过super.sum()也可以直接调用父类的方法
        this.z=z
    }
}

var pop = new son(1, 2)
pop.sum()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值