1. 程式人生 > 其它 >ES6中類的 例項屬性、例項方法、靜態屬性、靜態方法總結

ES6中類的 例項屬性、例項方法、靜態屬性、靜態方法總結

ES6出現了class的概念,其實和其他語言中的class的使用方法大同小異,這裡簡單總結以下js中相關的使用方法。

例項屬性和方法

  • 直接寫在類中,掛載在this物件上;
  • 只能通過設定get和set方法拿到,不然是預設的private 從外界無法獲取也無法修改;
  • 在外界只能建立例項後,通過例項取到。
// 定義
class TestClass extends Test {
	constructor(props = {}) {
		super(props)
	}

	this.prop = 1 // 例項屬性
	get prop() {
		return this.prop
	}
	set prop(value) {
		this.prop = value
	}
}

// 使用
const test = new Test()
test.prop = 2 // 實際上呼叫了裡面寫的 set 方法

靜態屬性和方法

  • 也是直接寫在類中,但要加 static 關鍵字;
  • 定義靜態方法也是一樣,在方法前面加上 static 關鍵字;
  • 例項方法中拿到靜態屬性要通過 類名 獲取,靜態方法中可以通過this獲取
// 定義
class TestClass extends Test {
	constructor(props = {}) {
		super(props)
	}

	static prop = 1 // 靜態屬性

	// 例項方法中要用類名拿靜態屬性
	setProp(value) {
		TestClass.prop = value + 1
	}

	// 靜態方法中用this拿到靜態屬性
	static get prop() {
		return this.prop
	}
	static set prop(value) {
		this.prop = value
	}
}

// 使用
const test = TestClass.prop
TestClass.prop = test + 1