javascript中Class(類)的介紹和使用方法
簡言
在面向?qū)ο缶幊讨校╫bject-oriented programming), 一個(gè) 類 定義了一個(gè)對象(object’s)的特征。類是定義對象屬性(properties)和方法(methods)的模板,是用來繪制具體對象實(shí)例的“藍(lán)圖”。
js中類是用于創(chuàng)建對象的模板,他們用代碼封裝數(shù)據(jù)以處理該數(shù)據(jù),JS 中的類建立在原型上的。
雖然js通過構(gòu)造函數(shù)和原型鏈也能實(shí)現(xiàn)面向?qū)ο缶幊痰奶匦?,但是直接?shí)現(xiàn)的話比較復(fù)雜,所以JavaScript 提供了Class(類)模型,它是把面向?qū)ο缶幊烫匦詮脑偷幕A(chǔ)上實(shí)現(xiàn)的,從而能夠更為直觀地在 JavaScript 中使用基于類的面向?qū)ο缶幊讨械母拍睢?/p>
Class(類)
實(shí)際上,類是“特殊的函數(shù)”,就像你能夠定義的函數(shù)表達(dá)式和函數(shù)聲明一樣。
定義類
類語法有兩個(gè)組成部分:類表達(dá)式和類聲明。類聲明和類表達(dá)式的主體都執(zhí)行在嚴(yán)格模式下。比如,構(gòu)造函數(shù),靜態(tài)方法,原型方法,getter 和 setter 都在嚴(yán)格模式下執(zhí)行。
類聲明
定義類的一種方法是使用類聲明。要聲明一個(gè)類,你可以使用帶有class關(guān)鍵字的類名。
類聲明不會(huì)提升。你首先需要聲明你的類,然后再訪問它,否則將拋出ReferenceError
class Rectangle { constructor(height, width) { this.height = height; this.width = width; } }
類表達(dá)式
類表達(dá)式是定義類的另一種方法。類表達(dá)式可以命名或不命名。命名類表達(dá)式的名稱是該類體的局部名稱。(不過,可以通過類的 (而不是一個(gè)實(shí)例的) name 屬性來檢索它)。
// 未命名/匿名類 let Rectangle = class { constructor(height, width) { this.height = height; this.width = width; } }; console.log(Rectangle.name); // output: "Rectangle" // 命名類 let Rectangle = class Rectangle2 { constructor(height, width) { this.height = height; this.width = width; } }; console.log(Rectangle.name); // 輸出:"Rectangle2"
類體和方法定義
一個(gè)類的類體是一對花括號/大括號 {} 中的部分。這是你定義類成員的位置,如方法或構(gòu)造函數(shù)。
constructor方法是一個(gè)特殊的方法,這種方法用于創(chuàng)建和初始化一個(gè)由class創(chuàng)建的對象。一個(gè)類只能擁有一個(gè)名為“constructor”的特殊方法。如果類包含多個(gè)constructor的方法,則將拋出 一個(gè)SyntaxError 。
一個(gè)構(gòu)造函數(shù)可以使用 super 關(guān)鍵字來調(diào)用一個(gè)父類的構(gòu)造函數(shù)。
類里面的方法和對象里的方法寫法一樣,不過它可以加些特殊的修飾詞,修飾詞不同作用不同,例如加 static就變了靜態(tài)方法,添加#就變成了私有方法。
類的 constructor
constructor 是一種用于創(chuàng)建和初始化class創(chuàng)建的對象的特殊方法。
constructor函數(shù)創(chuàng)建類對象實(shí)例時(shí)的new息息相關(guān)。
語法
constructor([arguments]) { ... }
特點(diǎn)
在一個(gè)類中只能有一個(gè)名為“constructor”的特殊方法。一個(gè)類中出現(xiàn)多次構(gòu)造函數(shù) (constructor)方法將會(huì)拋出一個(gè) SyntaxError 錯(cuò)誤。
在一個(gè)構(gòu)造方法中可以使用super關(guān)鍵字來調(diào)用一個(gè)父類的構(gòu)造方法。
如果沒有顯式指定構(gòu)造方法,則會(huì)添加默認(rèn)的 constructor 方法。
如果不指定一個(gè)構(gòu)造函數(shù) (constructor) 方法,則使用一個(gè)默認(rèn)的構(gòu)造函數(shù) (constructor)。
對于基類,默認(rèn)構(gòu)造函數(shù)是:
constructor() {}
對于派生類(有祖先類)的默認(rèn)構(gòu)造函數(shù):
constructor(...args) { super(...args); }
例子
class Polygon { constructor() { this.name = "Polygon"; } } class Square extends Polygon { constructor() { super(); } } class Rectangle {} Object.setPrototypeOf(Square.prototype, Rectangle.prototype); console.log(Object.getPrototypeOf(Square.prototype) === Polygon.prototype); //false console.log(Object.getPrototypeOf(Square.prototype) === Rectangle.prototype); //true let newInstance = new Square(); console.log(newInstance.name); //Polygon
類繼承(extends)
extends 關(guān)鍵字用于類聲明或者類表達(dá)式中,以創(chuàng)建一個(gè)類,該類是另一個(gè)類的子類,也叫派生類。
特點(diǎn)
- 派生類創(chuàng)建構(gòu)造函數(shù)時(shí)要帶上super(),不然會(huì)報(bào)錯(cuò)。
- 派生類會(huì)繼承類的方法和屬性,并可以在類實(shí)例和類體中使用。
- 派生類重寫的同名方法和屬性,將會(huì)覆蓋基類的方法和屬性。
class Animal { name = ""; constructor(name) { this.name = name; } eat() { console.log("吃東西"); } } class Cat extends Animal { constructor(name, color) { super(name); // 通過this可獲取祖先類的屬性 this.color = color; } skill() { console.log(this.name + "抓老鼠"); } eat2() { // 通過this可獲取祖先類的方法 this.eat(); console.log(`${this.color}貓` + this.name + "吃東西"); } } const tom = new Cat("湯姆", "skyblue"); tom.eat2(); // 繼承Animal的方法 tom.skill();
類體中的修飾詞
私有屬性和方法(#)
類屬性在默認(rèn)情況下是公有的,但可以使用增加哈希前綴 # 的方法來定義私有類字段(私有屬性和方法統(tǒng)稱私有字段)。
class ClassWithPrivateField { #privateField; } class ClassWithPrivateMethod { #privateMethod() { return "hello world"; } } class ClassWithPrivateStaticField { static #PRIVATE_STATIC_FIELD; } class ClassWithPrivateStaticMethod { static #privateStaticMethod() { return "hello world"; } }
私有字段分為私有實(shí)例字段和私有靜態(tài)字段:
- 私有實(shí)例字段使用 #名稱(發(fā)音為“哈希名稱”)聲明,這些名稱以 # 開頭。即 # 是名稱本身的一部分,聲明和訪問時(shí)也需要加上。它只能在類體中訪問和修改,不能在外面直接使用和修改。
- 私有靜態(tài)字段。在私有實(shí)例字段前面加 static。在類體中只能通過類本身調(diào)用和修改。
class Obj { #name = ""; // 私有,只能在里面使用 static #age = 18; // 私有,只能在里面被類本身使用 constructor(name, age) { this.#name = name; Obj.#age = age; } base() { console.log(`${this.#name} ${Obj.#age}`); } } const obj1 = new Obj("hh", 20); obj1.base();
靜態(tài)屬性和方法(static)
類(class)通過 static 關(guān)鍵字定義靜態(tài)方法。不能在類的實(shí)例上調(diào)用靜態(tài)方法,而應(yīng)該通過類本身調(diào)用。這些通常是實(shí)用程序方法,例如創(chuàng)建或克隆對象的功能。
特點(diǎn):
- 靜態(tài)方法調(diào)用同一個(gè)類中的其他靜態(tài)方法,可使用 this 關(guān)鍵字。
- 靜態(tài)方法調(diào)用直接在類上進(jìn)行,不能在類的實(shí)例上調(diào)用。
- 非靜態(tài)方法中,不能直接使用 this 關(guān)鍵字來訪問靜態(tài)方法。而是要用類名來調(diào)用或者用構(gòu)造函數(shù)的屬性來調(diào)用該方法。
class Tripple { static tripple(n = 1) { return n * 3; } } class BiggerTripple extends Tripple { static tripple(n) { return super.tripple(n) * super.tripple(n); } } console.log(Tripple.tripple()); // 3 console.log(Tripple.tripple(6)); // 18 let tp = new Tripple(); console.log(BiggerTripple.tripple(3)); // 81(不會(huì)受父類實(shí)例化的影響) console.log(tp.tripple()); // 'tp.tripple 不是一個(gè)函數(shù)'.
公有字段
公有靜態(tài)字段和公有實(shí)例字段都是可編輯、可枚舉和可配置的屬性。因此,不同于私有對應(yīng)值(private counterpart)的是,它們參與原型的繼承。
默認(rèn)就是公有字段??梢栽陬悓ο髮?shí)例中使用和修改。
Static initialization blocks
靜態(tài)初始化塊在類中聲明。
特點(diǎn):
- 在類體中 用static修飾的{}括號內(nèi)容區(qū)域。里面this指向類的構(gòu)造函數(shù)對象,可以使用this調(diào)用其他公共靜態(tài)字段。
- {}內(nèi)可以聲明變量,這包括 var、function、const 和 let 聲明。
- 可以有多個(gè) 靜態(tài)初始化塊。
class MyClass { static field1 = console.log("static field1"); static { console.log("static block1"); } static field2 = console.log("static field2"); static { console.log("static block2"); } } // 'static field1' // 'static block1' // 'static field2' // 'static block2'
如何從類外的對象訪問類的私有實(shí)例字段。
let getDPrivateField; class D { #privateField; constructor(v) { this.#privateField = v; } static { getDPrivateField = (d) => d.#privateField; } } console.log(getDPrivateField(new D("private"))); // 'private'
結(jié)語
類編程室es6的,不是兼容所有版本的瀏覽器。
到此這篇關(guān)于javascript中Class(類)的介紹和使用方法的文章就介紹到這了,更多相關(guān)js中Class(類)介紹和使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
瀏覽器圖片選擇預(yù)覽、旋轉(zhuǎn)、批量上傳的JS代碼實(shí)現(xiàn)
這篇文章主要介紹了瀏覽器圖片選擇預(yù)覽、旋轉(zhuǎn)、批量上傳的JS代碼實(shí)現(xiàn),有需要的朋友可以參考一下2013-12-12JS首屏加載時(shí)間優(yōu)化的解決方法總結(jié)
首屏加載時(shí)間是一個(gè)衡量網(wǎng)頁性能和用戶體驗(yàn)的關(guān)鍵指標(biāo),這個(gè)問題無論是在面試中還是在項(xiàng)目開發(fā)中都占有極其高的權(quán)重,本文為大家整理了幾種JS中優(yōu)化首屏加載時(shí)間的方法,希望對大家有所幫助2024-02-02支付寶小程序從手動(dòng)埋點(diǎn)到自動(dòng)埋點(diǎn)的實(shí)現(xiàn)過程
埋點(diǎn)的意思是在你想要的數(shù)據(jù)節(jié)點(diǎn)出進(jìn)行設(shè)置,可以方便進(jìn)行采集,下面這篇文章主要給大家介紹了關(guān)于支付寶小程序從手動(dòng)埋點(diǎn)到自動(dòng)埋點(diǎn)的相關(guān)資料,需要的朋友可以參考下2022-03-0318個(gè)JavaScript編寫簡潔高效代碼的技巧分享
在這篇文章中,小編將和大家分享18個(gè)JavaScript技巧,以及一些你應(yīng)該知道的示例代碼,以編寫簡潔高效的代碼,感興趣的小伙伴快跟隨小編一起學(xué)習(xí)一下吧2024-01-01JavaScript實(shí)現(xiàn)流星雨效果的示例代碼
這篇文章主要為大家詳細(xì)介紹了如何利用JavaScript實(shí)現(xiàn)簡易的流星雨的效果,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-06-06談?wù)凧avaScript數(shù)組常用方法總結(jié)
本篇文章主要介紹了談?wù)凧avaScript數(shù)組常用方法總結(jié),在JavaScript中,我們需要時(shí)常對數(shù)組進(jìn)行操作。一起跟隨小編過來看看吧2017-01-01