Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

es6继承 #46

Open
into-piece opened this issue Apr 27, 2021 · 2 comments
Open

es6继承 #46

into-piece opened this issue Apr 27, 2021 · 2 comments

Comments

@into-piece
Copy link
Owner

into-piece commented Apr 27, 2021

阮一峰 es继承

子类必须在constructor方法中调用super方法,否则新建实例时会报错。这是因为子类自己的this对象,必须先通过父类的构造函数完成塑造,得到与父类同样的实例属性和方法,然后再对其进行加工,加上子类自己的实例属性和方法。如果不调用super方法,子类就得不到this对象。

ES5 的继承,实质是先创造子类的实例对象this,然后再将父类的方法添加到this上面(Parent.apply(this))。ES6 的继承机制完全不同,实质是先将父类实例对象的属性和方法,加到this上面(所以必须先调用super方法),然后再用子类的构造函数修改this。

@into-piece
Copy link
Owner Author

into-piece commented Apr 27, 2021

es5 组合继承

function Parent(){
    this.familyName = 'James'
}

Parent.prototype.skill = ()=>{
    console.log('to play basketball')
}

function Child(){
    this.name = 'Lebron'
    // 把父类构造函数当做普通方法执行,改变this指向
    Parent.call(this) //相当于 Child.familyName = 'James'
}

// Object.create方法第一个参数会把创建空对象的__proto__指向传入的对象
// 相当于 Child.prototype.__proto__ = Parent.prototype 但是Child.prototype.__proto__这种直接操作__proto__的方式IE浏览器并不支持
Child.prototype = Object.create(Parent.prototype)
Child.prototype.constructor = Child;

Child.prototype.rap = ()=>{
    console.log('gigigigigigi')
}

let c = new Child

console.log(c.name,c.familyName,c.skill(),c.rap())

@into-piece
Copy link
Owner Author

Object.create()方法创建一个新对象,使用现有的对象来提供新创建的对象的__proto__

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant