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());