class 是 ES6 的新特性,可以用來定義一個類,實際上,class 只是一種語法糖,它是構造函數的另一種寫法。
class Person {
}
typeof Person // "function"
Person.prototype.constructor === Person // true
🚗 使用
用法和使用構造函數一樣,通過 new 來生成對象實例
class Person {
}
let jon = new Person()
🚌 constructor
每個類都必須要有一個 constructor,如果沒有顯示聲明,js 引擎會自動給它添加一個空的構造函數:
class Person {
}
// 等同於
class Person {
constructor () {
}
}
🏎 實例屬性和方法,原型屬性和方法
定義於 constructor 內的屬性和方法,即定義在 this 上,屬於實例屬性和方法,否則屬於原型屬性和方法。
class Person {
constructor (name) {
this.name = name
}
say () {
console.log('hello')
}
}
let jon = new Person()
jon.hasOwnPrototype('name') // true
jon.hasOwnPrototype('say') // false
🚓 屬性表達式
let methodName = 'say'
class Person {
constructor (name) {
this.name = name
}
[methodName] () {
console.log('hello')
}
}
🚚 靜態方法
不需要通過實例對象,可以直接通過類來調用的方法,其中的 this 指向類本身
class Person {
static doSay () {
this.say()
}
static say () {
console.log('hello')
}
}
Person.doSay() // hello
靜態方法可以被子類繼承
// ...
class Sub extends Person {
}
Sub.doSay() // hello
可以通過 super 對象訪問
// ...
class Sub extends Person {
static nice () {
return super.doSay()
}
}
Sub.nice() // hello
🚜 嚴格模式
不需要使用 use strict,因爲只要代碼寫在類和模塊內,就只能使用嚴格模式。
🏍 提升
class 不存在變量提升。
new Person() // Uncaught ReferenceError: Person is not defined
class Person {
}
🚄 name 屬性
name 屬性返回了類的名字,即緊跟在 class 後面的名字。
class Person {
}
Person.name // Person
🚈 this
默認指向類的實例。
🚂 取值函數(getter)和存值函數(setter)
class Person {
get name () {
return 'getter'
}
set name(val) {
console.log('setter' + val)
}
}
let jon = new Person()
jon.name = 'jon' // setter jon
jon.name // getter
🛥 class 表達式
如果需要,可爲類定義一個類內部名字,如果不需要,可以省略:
// 需要在類內部使用類名
const Person = class Obj {
getClassName () {
return Obj.name
}
}
// 不需要
const Person = class {}
立即執行的 Class:
let jon = new class {
constructor(name) {
this.name = name
}
sayName() {
console.log(this.name)
}
}('jon')
jon.sayName() //jon
🚀 參考
- 《ECMAScript 6 入門》Class 的基本語法 by 阮一峯