ES6class继承

class 类

// function Dog(breed,color,age){
//     this.breed = breed;
//     this.color = color;
//     this.age = age;
// }
// Dog.prototype.bark = function(){
//     alert("汪汪汪")
// }
// var dog = new Dog("泰迪","棕色",5);
// ------------- ES6写法  -------------------------
class Dog {
    constructor(breed, color, age) {
        this.breed = breed;
        this.color = color;
        this.age = age;
    }
    bark(){
    	alert("汪汪汪")
    }
}
var dog = new Dog("泰迪","棕色",5);
console.log(typeof Dog);//function
console.log(Dog === Dog.prototype.constructor);

通过以上的代码,我们发现,class的本质是函数,类本身指向的就是构造函数。

ES6的class可以看作是构造函数的语法糖。它的绝大部分功能,ES5都可以做到,新的class写法只是让对象原型写法更加清晰,更加符合面向对象编程的语法而已。

var arr = new Array();
var arr2 = [];//就是上面new Array的语法糖。

ES6继承

class Dog {
    constructor(breed, color, age) {
        this.breed = breed;
        this.color = color;
        this.age = age;
    }
    bark(){
    	alert("汪汪汪")
    }
}
class Haskie extends Dog{
    constructor(breed, color, age, name){
        //super在这里就相当于调用了父类的构造函数。
        //super不可以省略
        super(breed, color, age);
        this.name = name;
    }
}
const h2 = new Haskie("哈士奇","黑白",5,"二哈");
console.log(h2.name,h2.breed,h2.color,h2.age);
h2.bark();

super

super关键字,既可以当函数来使用,也可以当对象来使用。

第一种情况:super作为函数调用时,表示父类的构造函数。

作为函数时,super()只能用在子类的构造函数中

class A{}
class B extends A{
    constructor(){}
    fn(){
    	super();//报错
    }
}

第二种情况

super作为对象时,在普通方法中,指向父类的原型对象。

class A{
    p(){
    	return 1;
    }
}
class B extends A{
    constructor(){
        super();
        console.log(super.p());
    }
}
let b = new B();
console.log(b.p());

造函数。

作为函数时,super()只能用在子类的构造函数中

class A{}
class B extends A{
    constructor(){}
    fn(){
    	super();//报错
    }
}

第二种情况

super作为对象时,在普通方法中,指向父类的原型对象。

class A{
    p(){
    	return 1;
    }
}
class B extends A{
    constructor(){
        super();
        console.log(super.p());
    }
}
let b = new B();
console.log(b.p());
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值