ES6引入了class类的概念,创建的每一个class类,都会有一个constructor()方法,该方法是一种用于创建和初始化class创建的对象的特殊方法--构造函数方法。
eg:
class Animal {
constructor() {
this.name = "animal";
}
}
let animal = new Animal();
console.log(animal.name);
//输出:animal,所以 Animal类里的constructor()方法里的 this 指向的是被创建的实例对象
如果一个类没有指定constructor() 方法,则会添加默认的constructor()方法;
class Animal(){}
等同于
class Animal(){
constructor(){} //默认的constructor方法
}
一个类只允许有一个constructor()方法,如果出现多个,则会报:Uncaught SyntaxError: A class may only have one constructor
类的继承:
子类继承父类,会同时继承父类的私有属性方法,constructor()为私有属性方法
class Animal {
constructor() {
this.name = "animal";
this.age = "20";
}
}
// Dog 继承 Animal
class Dog extends Animal {
constructor() {
super(); //使用extend必须使用super(); super关键字来调用父类的构造方法;
this.name = "dog";
}
}
let animal = new Animal();
console.log(animal.name + '-' + animal.age);
//输出:animal-20
let dog = new Dog();
console.log(dog.name + '-' + dog.age);
//输出:dog-20 age继承父类的 age:20
如果使用Object.setPrototypeOf方法改变被继承的类的原型,构造函数(constructor)不会被改变继承,因为Object.setPrototypeOf方法是针对对象实例的,而不是构造函数(类):
class Food { }
Object.setPrototypeOf(Dog.prototype, Food.prototype);
console.log(Object.getPrototypeOf(Dog.prototype) === Animal.prototype); //false
console.log(Object.getPrototypeOf(Dog.prototype) === Food.prototype); //true
let dog = new Dog();
console.log(dog.age);
//输出:20 ,Dog的原型被改变,但是仍然调用的是Animal的构造函数
如有错误,请指出,多多指教。