“携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第1天,点击查看活动详情
- es6主流方法extends继承 . js继承现在都是使用es6新增的类,虽然不是所有的浏览器都完美支持,但是工程化会利用babel转化成es5代码,所以大家要熟练掌握,并使用。
class Animal {
constructor(name, age) {
this.name = name;
this.age = age;
}
paly() {
console.log("玩");
}
}
class Cat extends Animal {
constructor(name, age) {
super(name, age);
}
eat() {
console.log("吃鱼");
}
}
class Tom extends Cat {
constructor(age) {
super("tom", age);
}
eat() {
console.log("吃杰瑞");
}
}
const tom = new Tom(18);
console.log(tom);
tom.paly();
2.es5继承方式 2.1原型链继承 原型链是最简单的继承。 缺点: 原型链继承共用属性和方法,如果属性是引用类型,所有实例的属性都会指向同一个内存地址,修改一个,所有实例的属性都会更改,造成数据污染
function Person(name) {
this.name = name;
this.age = 18;
this.food = ["肉", "蔬菜", "水果"];
}
Person.prototype.say = function () {
console.log(this.name + "说爱你");
};
function Adult(name) {
this.name = name;
}
Adult.prototype = new Person("张三");
const ls = new Adult("李四");
console.log(ls);
//Person { name: '李四' }
ls.say();
//李四说爱你
console.log(ls.food);
const ww = new Adult("王五");
console.log(ww)
//Person { name: '王五' }
ww.say()
//王五说爱你
ww.food.push('小米粥')
console.log(ww.food,ls.food)
// [ '肉', '蔬菜', '水果', '小米粥' ] [ '肉', '蔬菜', '水果', '小米粥' ]
2.2构造函数继承 构造函数继承又叫对象冒充继承,利用call和apply改变构造函数中的this,因为构造函数只是一个函数,所以可使ClassB构造函数创建的this,调用ClassA指定this为classB中创建的this,ClassB就会收到ClassA的构造函数中定义的属性和方法。 缺点不能继承原型对象上的属性和方法
function ClassA(name){
this.name=name
this.say=function(){console.log('say by')}
}
ClassA.prototype.eat=function(){
console.log('吃肉')
}
function ClassB(name){
ClassA.call(this,name)
}
const b=new ClassB('xiaob')
console.log(b)
ClassB { name: 'xiaob', say: [Function (anonymous)] }
b.say()
//say by
b.eat()
//报错
2.3组合继承 既然,原型链继承 和构造函数继承都有各自的优点和缺点那么扬长避短,结合两种继承的优点组合而成的方法就是组合继承,使用原型链接成方法,使用构造函数继承属性。 缺点:之前原型对象上存在的属性和方法会被覆盖,且无法完美扩展 创建多个实例父类会多次被调用,浪费性能
2.4 寄生继承 利用Object.create获取一份目标对象的浅拷贝,然后添加一些方法避免污染基类,解决了组合继承,原型对象扩展难的问题
2.5组合寄生方式继承
function inheritPrototype(subType, superType) {
var prototype = Object.create(superType.prototype);
prototype.constructor = subType;
subType.prototype = prototype;
}
function SuperType(name) {
this.name = name;
this.colors = ["red", "blue", "green"];
}
SuperType.prototype.sayName = function () {
console.log(this.name);
};
function SubType(name, age) {
console.log(name,age)
SuperType.call(this, name);
this.age = age;
}
inheritPrototype(SubType, SuperType);
SubType.prototype.sayAge = function () {
console.log(this.age);
};
var p=new SuperType()
p.satAge()
//报错
var instance = new SubType("二龙湖",18);
instance.sayName()
扩展不污染父类