1、class寫法
class Example { constructor(name) { this.name = name } func() { console.log(this.name) } }
2、function寫法
'use strict' function Example(name) { if (!new.target) { throw new TypeError(`Class constructor Example cannot be invoked without 'new'`) } this.name = name } Object.defineProperty(Example.prototype, 'func', { value: function () { if (new.target) { throw new TypeError(`Example.prototype.func is not a constructor`) } console.log(this.name) }, enumerable: false, })
'use strict'
: class中的代碼全部都是在一個嚴格模式下,對于一些不安全的操作會拋出錯誤,使代碼更加規(guī)范。
function Example(name) { ... }
: 這是一個函數(shù)聲明,函數(shù)名為?Example
,它接受一個參數(shù)?name
。這個函數(shù)充當(dāng)了類的構(gòu)造函數(shù)的角色。函數(shù)名與class名相同。
if (!new.target) { ... }
: 這一行檢查函數(shù)是否通過?new
?關(guān)鍵字調(diào)用。class寫法只能通過new關(guān)鍵字調(diào)用的。否則就會報如下錯誤而構(gòu)造函數(shù)(普通函數(shù))可以直接調(diào)用也可以通過new關(guān)鍵字來調(diào)用。
new.target
?是一個元屬性,指向當(dāng)前正在執(zhí)行的構(gòu)造函數(shù)或函數(shù)。如果函數(shù)沒有通過?new
?調(diào)用,意味著它被當(dāng)做普通函數(shù)調(diào)用,而不是構(gòu)造函數(shù),因此會拋出一個?TypeError
。
throw new TypeError(...)
:如果函數(shù)沒有通過?new
?關(guān)鍵字調(diào)用,拋出一個類型錯誤,指示?Example
?構(gòu)造函數(shù)不能在沒有?new
?關(guān)鍵字的情況下被調(diào)用。
this.name = name
: 這一行將參數(shù)?name
?分配給新創(chuàng)建的對象的?name
?屬性。在函數(shù)內(nèi)部,this
?指向的是正在被創(chuàng)建的對象。
class中的方法是不會被枚舉的。所以需要通過Object.defineProperty(Example.prototype, 'func', { ... })
: 這一行定義了一個不可枚舉的屬性?func
,它是?Example.prototype
?對象的一個屬性。
value: function () { ... }
: 這是給?func
?屬性賦值,這個值是一個函數(shù),實現(xiàn)了類中的?func
?方法。
通過new關(guān)鍵字去class中的方法,比如:
文章來源:http://www.zghlxwxcb.cn/news/detail-853134.htmlnew Example.prototype.func()
這樣也是會報錯的,但是在構(gòu)造函數(shù)(普通函數(shù)中)是可以這樣調(diào)用的。因此這里也需要進行判斷。if (new.target) { ... }
: 這一行再次檢查?func
?方法是否通過?new
?關(guān)鍵字調(diào)用。如果是,則拋出一個?TypeError
,因為?func
?方法不應(yīng)該被當(dāng)做構(gòu)造函數(shù)來調(diào)用。文章來源地址http://www.zghlxwxcb.cn/news/detail-853134.html
到了這里,關(guān)于前端開發(fā)攻略---JS將class轉(zhuǎn)換為function。滿分寫法無死角的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!