【ES6(2015)】Class (类)
生活随笔
收集整理的這篇文章主要介紹了
【ES6(2015)】Class (类)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
文章目錄
- 1. 聲明類
- 2. Setters & Getters
- 3. 靜態(tài)方法
- 4. 繼承
Javascript是一種基于對象(object-based)的語言,你遇到的所有東西幾乎都是對象。但是,它又不是一種真正的面向?qū)ο缶幊?#xff08;OOP)語言,因為它的語法中沒有class(類)。
對于面向?qū)ο缶幊潭?#xff0c;更關(guān)注類的聲明、屬性、方法、靜態(tài)方法、繼承、多態(tài)、私有屬性。
1. 聲明類
ES5 中聲明(構(gòu)造方法):
let Animal = function(type) {// 屬性this.type = type// 方法this.walk = function() {console.log( `I am walking` )} } Animal.prototype.run = function() {console.log( `I am running` ) }let dog = new Animal('dog') let monkey = new Animal('monkey')ES6 聲明Class類:
class Animal {// 構(gòu)造函數(shù)constructor(type) {this.type = type}// 方法walk() {console.log( `I am walking` )} } let dog = new Animal('dog') let monkey = new Animal('monkey')class 的方式是 function 方式的語法糖
2. Setters & Getters
對于類中的屬性,可以直接在 constructor中通過 this 直接定義,還可以直接在類的頂層來定義:
class Animal {constructor(type, age) {this.type = typethis._age = age}get age() {return this._age}set age(val) {this._age = val} }設(shè)置制度屬性只需要把set方法去掉即可。
set/get可以控制在滿足條件下才執(zhí)行:
let #age = 1 class Animal {constructor(type) {this.type = type}get age() {return #age}set age(val) {if (val > 0 && val < 10) {#age = val}} }3. 靜態(tài)方法
靜態(tài)方法是面向?qū)ο笞畛S玫墓δ?#xff0c;在 ES5 中利用 function 實現(xiàn)的類是這樣實現(xiàn)一個靜態(tài)方法的。
let Animal = function(type) {this.type = typethis.walk = function() {console.log( `I am walking` )} }Animal.eat = function(food) {console.log( `I am eating` ) }在 ES6 中使用 static 的標(biāo)記是不是靜態(tài)方法,代碼如下:
class Animal {constructor(type) {this.type = type}walk() {console.log( `I am walking` )}static eat() {console.log( `I am eating` )} }靜態(tài)方法是直接用類名訪問的。
4. 繼承
在 ES5 中怎么實現(xiàn)繼承:
// 定義父類 let Animal = function(type) {this.type = type } Animal.prototype.walk = function() {console.log( `I am walking` ) }// 定義子類 let Dog = function() {// 初始化父類Animal.call(this, 'dog')this.run = function() {console.log('I can run')} } // 繼承 Dog.prototype = Animal.prototypeES6 中的繼承:
// 父類 class Animal {constructor(type) {this.type = type}walk() {console.log( `I am walking` )} } // 子類繼承父類 class Dog extends Animal {constructor () {super('dog')}run () {console.log('I can run')} }雖然 ES6 在類的定義上僅是 ES5 定義類的語法糖,但是從開發(fā)者的角度而言,開發(fā)更有效率了,代碼可閱讀性大大提升。
總結(jié)
以上是生活随笔為你收集整理的【ES6(2015)】Class (类)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【ES11(2020)】可选链操作符和空
- 下一篇: 华为鸿蒙系统真的好吗,鸿蒙系统真的成熟吗