js中的继承

8次阅读

共计 825 个字符,预计需要花费 3 分钟才能阅读完成。

js 中的继承

ES5 prototype

Parent.prototype.__proto = Child.prototype
Object.setPrototypeOf(Child.prototype, Parent.prototype)

ES6 class
类继承

ES5 prototype 实现继承
function Parent(){
this.name = ‘parent name’;
}
Parent.prototype.eat = function(){
consle.log(‘parent eat’);
}
function Child(){
Parent.call(this);// 改变 this
this.name = ‘child name’;
}
Child.prototype = Parent.prototype; // 这样不是继承,Parent 和 Child 变成了兄弟 关系
// 正确做法 一,儿子的原型 原型链 指向 父亲的原型
Child.prototype.__proto__ = Parent.prototype;
// 正确做法 二,
Object.setPrototypeOf(Child.prototype, Parent.prototype);

let child = new Child();
console.log(child.name);// parent name
child.eat(); // parent eat

class 类继承
class Parent{
constructor(){
this.name = ‘parent name’;
}
eat(){
console.log(‘parent eat’)
}
}

class Child extends Parent{
constructor(){
super();
consle.log(this)// child
}

}

let child = new Child();
console.log(child.name) // parent name , Child 找不到就拿父级的
child.eat()// parent eat

正文完
 0