ES6為JavaScript引入了類,但對於復雜的應用程序來說,它們可能過於簡單。類字段(也稱為類屬性)旨在通過私有和靜態成員來簡化構造函數。該提案目前處於TC39第3階段:候選階段,很可能會添加到ES2019(ES10)。 Node.js 12、Chrome 74和Babel目前支持私有字段。在我們了解類字段的實現方式之前,回顧一下ES6類很有用。 本文於2020年更新。有關更深入的JavaScript知識,請閱讀我們的書籍《JavaScript:從新手到忍者,第二版》。
關鍵要點
ES6類基礎
來自C 、C#、Java和PHP等語言的開發人員可能會對JavaScript的面向對象繼承模型感到困惑。因此,ES6引入了類。它們主要是語法糖,但提供了更熟悉的面向對象編程概念。類是一個對像模板,它定義了該類型的對象的行為方式。以下Animal類定義了通用動物(類通常用初始大寫字母表示,以區別於對象和其他類型):
class Animal { constructor(name = 'anonymous', legs = 4, noise = 'nothing') { this.type = 'animal'; this.name = name; this.legs = legs; this.noise = noise; } speak() { console.log(`${this.name} says "${this.noise}"`); } walk() { console.log(`${this.name} walks on ${this.legs} legs`); } }
類聲明始終在嚴格模式下執行。無需添加'use strict'。 構造函數方法在創建Animal類型的對象時運行。它通常設置初始屬性並處理其他初始化。 speak()和walk()是實例方法,它們添加了更多功能。現在可以使用new關鍵字從此類創建對象:
let rex = new Animal('Rex', 4, 'woof'); rex.speak(); // Rex says "woof" rex.noise = 'growl'; rex.speak(); // Rex says "growl"
Getter和Setter
Setter是僅用於定義值的特殊方法。類似地,Getter是僅用於返回值的特殊方法。例如:
class Animal { constructor(name = 'anonymous', legs = 4, noise = 'nothing') { this.type = 'animal'; this.name = name; this.legs = legs; this.noise = noise; } speak() { console.log(`${this.name} says "${this.noise}"`); } walk() { console.log(`${this.name} walks on ${this.legs} legs`); } // setter set eats(food) { this.food = food; } // getter get dinner() { return `${this.name} eats ${this.food || 'nothing'} for dinner.`; } } let rex = new Animal('Rex', 4, 'woof'); rex.eats = 'anything'; console.log( rex.dinner ); // Rex eats anything for dinner.
子類或子類
將一個類用作另一個類的基類通常是可行的。 Human類可以使用extends關鍵字繼承Animal類中的所有屬性和方法。可以根據需要添加、刪除或更改屬性和方法,以便更容易和更清晰地創建人類對象:
class Animal { constructor(name = 'anonymous', legs = 4, noise = 'nothing') { this.type = 'animal'; this.name = name; this.legs = legs; this.noise = noise; } speak() { console.log(`${this.name} says "${this.noise}"`); } walk() { console.log(`${this.name} walks on ${this.legs} legs`); } }
super指的是父類,因此它通常是在構造函數中調用的第一個調用。在此示例中,Human speak()方法重寫了在Animal中定義的方法。現在可以創建Human的對象實例:
let rex = new Animal('Rex', 4, 'woof'); rex.speak(); // Rex says "woof" rex.noise = 'growl'; rex.speak(); // Rex says "growl"
靜態方法和屬性
使用static關鍵字定義方法允許在不創建對象實例的情況下在類上調用它。考慮Math.PI常量:在訪問PI屬性之前,無需創建Math對象。 ES6不支持與其他語言相同的靜態屬性,但可以將屬性添加到類定義本身。例如,Human類可以適應保留已創建多少個human對象的計數:
class Animal { constructor(name = 'anonymous', legs = 4, noise = 'nothing') { this.type = 'animal'; this.name = name; this.legs = legs; this.noise = noise; } speak() { console.log(`${this.name} says "${this.noise}"`); } walk() { console.log(`${this.name} walks on ${this.legs} legs`); } // setter set eats(food) { this.food = food; } // getter get dinner() { return `${this.name} eats ${this.food || 'nothing'} for dinner.`; } } let rex = new Animal('Rex', 4, 'woof'); rex.eats = 'anything'; console.log( rex.dinner ); // Rex eats anything for dinner.
類的靜態COUNT getter會相應地返回人類的數量:
class Human extends Animal { constructor(name) { // 调用Animal构造函数 super(name, 2, 'nothing of interest'); this.type = 'human'; } // 重写Animal.speak speak(to) { super.speak(); if (to) console.log(`to ${to}`); } }
ES2019類字段(新)
新的類字段實現允許在類的頂部、任何構造函數之外初始化公共屬性:
let don = new Human('Don'); don.speak('anyone'); // Don says "nothing of interest" to anyone don.eats = 'burgers'; console.log( don.dinner ); // Don eats burgers for dinner.
這等效於:
class Human extends Animal { constructor(name) { // 调用Animal构造函数 super(name, 2, 'nothing of interest'); this.type = 'human'; // 更新Human对象的计数 Human.count++; } // 重写Animal.speak speak(to) { super.speak(); if (to) console.log(`to ${to}`); } // 返回人类对象的个数 static get COUNT() { return Human.count; } } // 类的静态属性本身 - 不是其对象 Human.count = 0;
如果您仍然需要構造函數,則會在其運行之前執行初始化程序。
在上面的示例中,靜態屬性在定義類對像後以不優雅的方式添加到類定義對像中。使用類字段則無需這樣做:
console.log(`Humans defined: ${Human.COUNT}`); // Humans defined: 0 let don = new Human('Don'); console.log(`Humans defined: ${Human.COUNT}`); // Humans defined: 1 let kim = new Human('Kim'); console.log(`Humans defined: ${Human.COUNT}`); // Humans defined: 2
這等效於:
class MyClass { a = 1; b = 2; c = 3; }
ES6類中的所有屬性默認都是公共的,可以在類外部檢查或修改。在上面的Animal示例中,沒有任何東西可以阻止在不調用eats setter的情況下更改food屬性:
class MyClass { constructor() { this.a = 1; this.b = 2; this.c = 3; } }
其他語言通常允許聲明私有屬性。這在ES6中是不可能的,因此開發人員經常使用下劃線約定(_propertyName)、閉包、符號或WeakMap來解決這個問題。下劃線為開發人員提供了一個提示,但沒有任何東西可以阻止他們訪問該屬性。在ES2019中,私有類字段使用哈希#前綴定義:
class MyClass { x = 1; y = 2; static z = 3; } console.log( MyClass.z ); // 3
請注意,無法定義私有方法、getter或setter。 TC39第3階段:草案提案建議對名稱使用哈希#前綴,它已在Babel中實現。例如:
class MyClass { constructor() { this.x = 1; this.y = 2; } } MyClass.z = 3; console.log( MyClass.z ); // 3
立即受益:更簡潔的React代碼!
React組件通常具有與DOM事件綁定的方法。為了確保這解析為組件,有必要相應地綁定每個方法。例如:
class Animal { constructor(name = 'anonymous', legs = 4, noise = 'nothing') { this.type = 'animal'; this.name = name; this.legs = legs; this.noise = noise; } set eats(food) { this.food = food; } get dinner() { return `${this.name} eats ${this.food || 'nothing'} for dinner.`; } } let rex = new Animal('Rex', 4, 'woof'); rex.eats = 'anything'; // 标准setter rex.food = 'tofu'; // 完全绕过eats setter console.log( rex.dinner ); // Rex eats tofu for dinner.
當incCount定義為ES2019類字段時,可以使用ES6 =>胖箭頭將其賦值為函數,該函數自動綁定到定義對象。無需再添加綁定聲明:
class MyClass { a = 1; // .a是公共的 #b = 2; // .#b是私有的 static #c = 3; // .#c是私有的和静态的 incB() { this.#b++; } } let m = new MyClass(); m.incB(); // 运行正常 m.#b = 0; // 错误 - 私有属性不能在类外部修改
類字段:改進?
ES6類定義過於簡單。 ES2019類字段需要更少的代碼,提高了可讀性,並實現了一些有趣的面向對象編程的可能性。使用#表示私有性受到了一些批評,主要是因為它很醜陋,感覺像是一種技巧。大多數語言都實現了private關鍵字,因此嘗試在類外部使用該成員將被編譯器拒絕。 JavaScript是解釋型的。考慮以下代碼:
class Animal { constructor(name = 'anonymous', legs = 4, noise = 'nothing') { this.type = 'animal'; this.name = name; this.legs = legs; this.noise = noise; } speak() { console.log(`${this.name} says "${this.noise}"`); } walk() { console.log(`${this.name} walks on ${this.legs} legs`); } }
這將在最後一行拋出運行時錯誤,但這僅僅是嘗試設置屬性的嚴重後果。 JavaScript故意寬容,ES5允許修改任何對像上的屬性。雖然笨拙,但#符號在類定義之外是無效的。嘗試訪問myObject.#secret可能會拋出語法錯誤。這場辯論將繼續下去,但無論喜歡與否,類字段都已在多個JavaScript引擎中採用。它們將繼續存在。
關於JavaScript私有類字段的常見問題解答(FAQ)
JavaScript中的私有類字段提供了一種封裝或隱藏類中數據的方法,這是面向對象編程的基本原則。這種封裝確保對象的內部狀態只能通過類明確定義的方式更改。這導致代碼更健壯、更可預測,因為它可以防止外部代碼意外地以意外的方式更改對象的狀態。此外,私有字段可以幫助簡化類的接口,因為它們減少了公開給外部世界屬性和方法的數量。
在JavaScript中,私有類字段通過在字段名前添加哈希(#)符號來聲明。例如,要在類中聲明名為“value”的私有字段,可以編寫#value。然後,此字段只能在類的內部方法中訪問,而不能從類外部訪問。
不可以,JavaScript中的私有類字段無法從類外部訪問。這是設計使然,因為私有字段的主要用途之一是從外部世界隱藏內部數據。如果嘗試從類外部訪問私有字段,JavaScript將拋出語法錯誤。
可以,JavaScript類可以同時具有私有字段和公共字段。公共字段的聲明方式與私有字段相同,但沒有哈希(#)前綴。與只能從類內部訪問的私有字段不同,公共字段可以從類內部和外部訪問和修改。
JavaScript中的私有類字段和私有方法具有相似的用途,它們都提供了一種從外部世界隱藏類內部細節的方法。但是,它們的使用方式不同。私有字段用於存儲只能在類內部訪問的數據,而私有方法是只能在類內部調用的函數。
私有類字段是JavaScript中相對較新的特性,因此並非所有環境都支持它。在撰寫本文時,大多數主要瀏覽器(包括Chrome、Firefox和Safari)的最新版本都支持私有字段。但是,Internet Explorer不支持它們。如果您需要編寫可在所有瀏覽器中運行的代碼,則可能需要使用Babel之類的轉換器將代碼轉換為舊版瀏覽器可以理解的形式。
要在類的內部方法中使用私有類字段,只需使用其名稱(前面帶有哈希(#)符號)引用該字段即可。例如,如果您有一個名為“value”的私有字段,則可以在方法中像這樣訪問它:this.#value。
可以,可以在JavaScript的子類中使用私有類字段。但是,每個子類都有自己獨立的一組私有字段,這些字段不與超類或其他子類共享。這意味著如果子類聲明的私有字段與超類中的私有字段同名,則這兩個字段完全獨立,不會相互干擾。
不可以,JavaScript中的私有類字段不能在靜態方法中使用。這是因為靜態方法與類本身相關聯,而不是與類的實例相關聯,而私有字段只能在類的實例中訪問。
不可以,JavaScript中的私有類字段不包含在對象的屬性迭代中。這是設計使然,因為私有字段的主要用途之一是從外部世界隱藏內部數據。如果您需要迭代對象的屬性,則應改為使用公共字段或方法。
This response maintains the original image format and placement, and paraphrases the text while preserving the original meaning. The code examples remain largely unchanged as significant alteration would change the meaning.
以上是JavaScript的新私人班級字段以及如何使用它們的詳細內容。更多資訊請關注PHP中文網其他相關文章!