我來自非 JavaScript 編碼背景,我習慣做的一件事是將代碼封裝在類中。
所以我有一個類檔案并且它可以作業,但是對this.is的不斷參考缺乏某種優雅,這讓我認為我做錯了事。尤其是當我嘗試this.從方法中的“級別”代碼中進行參考時,我必須在區域變數中攜帶參考才能使其作業。
所以這是我所擁有的一個例子
class catalogue {
constructor () {
this.currentDoc = null;
this.dataDirectory = "data/";
}
loadJSON(filepath) {
// there is actual code in the real class
}
loadHTML(filePath) {
// there is actual code in the real class
}
loadExternalData() {
let filePath = `${this.dataDirectory}${this.currentDoc.filepath}`;
let dataIsJson = this.currentDoc.filepath.indexOf('.json') != -1;
let me = this; // this again :-(
if (dataIsJson) {
me.loadJSON(filePath);
} else {
me.loadHTML(filePath);
}
}
}
該loadExternalData()方法是從創建類實體的代碼中呼叫的。然后確定如何加載所需的資料,并根據資料型別呼叫各種方法。
Back in the 'old days' I would have stored a reference to the class as a property of the class and then used that to call methods. The main problem is that, as we know, this. is contextual and as soon as you use a conditional or anything similar the context, for some bizarre reason, changes and this. is not useful to my class any more.
So all of this makes me think that I am not doing things in a Javascripty fashion.
Is there an easier way to refer to methods and properties without using this. or do I need to look at reworking the code?
uj5u.com熱心網友回復:
你在做什么是完全正常和常見的。如果您擔心的是:
主要問題是,正如我們所知,這個。是背景關系的,一旦您使用條件或任何類似的背景關系,出于某種奇怪的原因,就會發生變化,而 this。對我的班級不再有用。
一個非常簡單的調整是改用箭頭函式類欄位,這樣this它將始終參考實體,而不必擔心更改呼叫背景關系。
class catalogue {
constructor () {
this.currentDoc = null;
this.dataDirectory = "data/";
}
loadJSON = (filepath) => {
// there is actual code in the real class
}
loadHTML = (filePath) => {
// there is actual code in the real class
}
loadExternalData = () => {
let filePath = `${this.dataDirectory}${this.currentDoc.filepath}`;
let dataIsJson = this.currentDoc.filepath.indexOf('.json') != -1;
if (dataIsJson) {
this.loadJSON(filePath);
} else {
this.loadHTML(filePath);
}
}
}
有沒有更簡單的方法來參考方法和屬性而不使用它
不是特別的,盡管我認為如果函式系結this正確,您也可以先將它們提取到獨立變數中,也許在函式的第一行。IMO 這不是改進,而是 YMMV。例如
loadExternalData() {
let filePath = `${this.dataDirectory}${this.currentDoc.filepath}`;
let dataIsJson = this.currentDoc.filepath.indexOf('.json') != -1;
可以改為
loadExternalData() {
const { dataDirectory, currentDoc } = this;
let filePath = `${dataDirectory}${currentDoc.filepath}`;
let dataIsJson = currentDoc.filepath.indexOf('.json') != -1;
Could also probably change the last line to
const dataIsJson = currentDoc.filePath.endsWith('.json');
to be precise.
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/359082.html
標籤:javascript class this
