js中的class类
函数声明和类声明之间的一个重要区别是函数声明会提升,类声明不会。需要先进行声明,再去访问,否则会报错
var father = new Father("我是爸爸")
class Father {
constructor(name) {
this.name = name;
}
putName(){
console.log(this.name)
}
}
// Uncaught ReferenceError: Cannot access 'Father' before initialization(在初始化之前无法访问“Person”)
constructor 方法
constructor 方法是类的默认方法,通过 new 命令生成对象实例时,自动调用该方法(默认返回实例对象 this)。一个类必须有 constructor 方法,如果没有显式定义,一个空的 constructor 方法会被默认添加。一个类只能拥有一个名为 “constructor” 的特殊方法,如果类包含多个 constructor 的方法,则将抛出 一个 SyntaxError 。
class Father {
constructor(name) {
this.name = name;
}
putName(){
console.log(this.name)
}
}
var father = new Father("我是爸爸")
father.putName()
- 在类中声明方法的时候,方法前不加 function 关键字
- 方法之间不要用逗号分隔,否则会报错
- 类的内部所有定义的方法,都是不可枚举的(non-enumerable)
- 一个类中只能拥有一个 constructor 方法
静态方法
静态方法可以通过类名调用,不能通过实例对象调用,否则会报错
class Father {
static putName(name){
console.log(name)
}
}
Father.putName("我是爸爸")
// var father = new Father()
// father.putName("我是爸爸 实例调用会报错") // Uncaught TypeError: father.putName is not a function
实例方法
实例方法可以通过实例对象调用,但同样不能通过类名调用,会报错
class Father {
constructor(){
this.putName = function(name){
console.log(name)
}
}
}
var father = new Father()
father.putName("我是爸爸")
// Father.putName("我是爸爸 类名调用会报错") // Uncaught TypeError: Father.putName is not a function
class继承
Class通过 extends 关键字实现继承。
class Father {
constructor(name,age){
this.name = name
this.age = age
}
putInfo(){
console.log(this.name,this.age)
}
}
class Son extends Father{
constructor(name,age){
super(name,age)
}
}
var son = new Son("我是儿子",18)
son.putInfo()