小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。
- 类的介绍 1 - 类的定义、语法和语义的区别 上一篇文章介绍了类的定义,语法和语义的区别,类本身是创建对象的模板,JavaScript 里面的类建立在原型的基础上,这一篇文章介绍类的方法中,基础的构造函数的用法
构造函数
构造函数 constructor 是一个特殊的方法,用来创建和初始化一个由 class 创建的对象,一个类只能有一个构造函数,如果有多个会抛出一个错误 SyntaxError
class Animal {
constructor() {
this.name = 'animal'
}
}
const animal = new Animal();
console.log(animal.name); // animal
如果类有父类,可以使用 super 来调用父类的构造函数,并传参数。在派生类中,必须先使用 super 调用父类的构造函数,才可以使用 this,否则会报引用错误
class Animal {
constructor(type) {
this.name = 'animal';
this.type = type;
}
}
class Dog extends Animal {
constructor(type) {
super(type);
this.name = 'dog name'
}
}
const dog = new Dog('dog');
console.log(dog.name); // dog name
console.log(dog.type); // dog
如果没有制定构造函数,则会使用默认的构造函数,对于基类
constructor() {}
对于派生类,则会默认使用 super 方法调用父类的构造函数
constructor(...args) {
super(...args);
}
以上为构造函数的介绍,可以思考下构造函数的写法,编译为 es5 可能的写法,欢迎点赞和评论~