一、ES6类
的类并不与其他语言的类完全相同,所具备的独特性正配合了 JS 的动态本质。
二、ES5 中的仿类结构
JS 在 ES5 及更早版本中都不存在类。与类最接近的是:创建一个构造器,然后将方法指派到该构造器的原型上。这种方式通常被称为创建一个自定义类型。
function StudentType(name){
this.name = name
}
StudentType.prototype.sayName = function(){
console.log(this.name)
}
let student = new StudentType('张三')
student.sayName() // 张三
console.log(student instanceof StudentType) // true
console.log(student instanceof Object) // true
此代码中的 PersonType 是一个构造器函数,并创建了单个属性 name 。 sayName() 方法被指派到原型上,因此在 PersonType 对象的所有实例上都共享了此方法。接下来,使用 new运算符创建了 PersonType 的一个新实例 person ,此对象会被认为是一个通过原型继承了PersonType 与 Object 的实例。
这种基本模式在许多对类进行模拟的 JS 库中都存在,而这也是 ES6 类的出发点。
三、基本的类声明
class StudentClass{
// 等价于StudentType构造器
constructor(name){
this.name = name
}
// 等价于StudentType.prototype.sayName
sayName(){
console.log(this.name)
}
}
let student = new StudentClass('kangyun')
student.sayName() // kangyun
console.log(student