接触过后端的朋友应该对Class并不陌生,ES6的Class借鉴的后端的类。
1.Class的基本用法
需要注意的是Class的名称首字母需要大写,Class本质上仍然是function,constructor中的写法跟ES5中构造函数的写法相似,使用类的时候必须通过new来实例化该对象
class Person{
constructor(name,age){
this.name = name
this.age = age
}
}
var p1 = new Person('lj',12)
console.log(p1)
结果为:Person {name: "lj", age: 12}
2.可以在Class中写方法
class Person{
constructor(name,age){
this.name = name
this.age = age
}
static isHuman(obj){
return obj instanceof Person
}
say(){
console.log('我叫'+this.name+'我今年'+this.age)
}
eat(){
console.log('eat...')
}
}
var p1 = new Person('lj',12)
console.log(p1)
console.log(Person.isHuman(1))
console.log(Person.isHuman(p1))
p1.say()
p1.eat()
console.log(Person.prototype)
结果为:Person {name: "lj", age: 12}
我叫lj我今年12
eat...
{constructor: ƒ, say: ƒ, eat: ƒ}
在Class中写方法可以直接在constructor下直接写,不需要加“,”进行隔开,另外在say这个方法中,我调用了当前对象的name和age,请直接用this调用。通过结果我们可以看出,我们在Class中写的方法实际上写到了该Class中的prototype中了。
3.在Class中写静态方法
class Person{
constructor(name,age){
this.name = name
this.age = age
}
static isHuman(obj){
return obj instanceof Person
}
}
var p1 = new Person('lj',12)
console.log(p1)
console.log(Person.isHuman(1))
console.log(Person.isHuman(p1))
这里我们需要注意的是,静态方法通过函数前加"static"字段声明,该Class中的静态方法不能通过实例来调用,只能通过该Class本身来调用,如Person.isHuman()
结果为:Person {name: "lj", age: 12}
false
true
4.Class的继承
在声明子类的时候,需要用extends字段来声明,如下:
class Person{
constructor(name,age){
this.name = name
this.age = age
}
static isHuman(obj){
return obj instanceof Person
}
say(){
console.log('我叫'+this.name+'我今年'+this.age)
}
eat(){
console.log('eat...')
}
}
class Coder extends Person{
constructor(name,age,money){
super(name,age)
this.money = money
}
}
var c1 = new Coder('zm',12,5000)
console.log(Coder.isHuman(1))
console.log(Coder.isHuman(c1))
console.log(c1)
c1.say()
c1.eat()
子类是会继承父类的静态方法的。需要注意的是,如果子类有其他的属性时,需要在子类的构造函数constructor中调用super(),参数为父类的属性名称,这样子类就全部继承父类的属性和方法了。
结果为:false
true
Coder {name: "zm", age: 12, money: 5000}
我叫zm我今年12
eat...