日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

【ES6(2015)】Class (类)

發布時間:2025/3/15 39 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【ES6(2015)】Class (类) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

文章目錄

  • 1. 聲明類
  • 2. Setters & Getters
  • 3. 靜態方法
  • 4. 繼承

Javascript是一種基于對象(object-based)的語言,你遇到的所有東西幾乎都是對象。但是,它又不是一種真正的面向對象編程(OOP)語言,因為它的語法中沒有class(類)。

對于面向對象編程而言,更關注類的聲明、屬性、方法、靜態方法、繼承、多態、私有屬性。

1. 聲明類

ES5 中聲明(構造方法):

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 {// 構造函數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} }

設置制度屬性只需要把set方法去掉即可。

set/get可以控制在滿足條件下才執行:

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. 靜態方法

靜態方法是面向對象最常用的功能,在 ES5 中利用 function 實現的類是這樣實現一個靜態方法的。

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 的標記是不是靜態方法,代碼如下:

class Animal {constructor(type) {this.type = type}walk() {console.log( `I am walking` )}static eat() {console.log( `I am eating` )} }

靜態方法是直接用類名訪問的。

4. 繼承

在 ES5 中怎么實現繼承:

// 定義父類 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.prototype

ES6 中的繼承:

// 父類 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 定義類的語法糖,但是從開發者的角度而言,開發更有效率了,代碼可閱讀性大大提升。

總結

以上是生活随笔為你收集整理的【ES6(2015)】Class (类)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。