嗨,我想優化我的代碼,所以我沒有很多 if 陳述句。我一直在嘗試優化這個代碼,女巫在一個類中
if (spot.charAt(1) === "P") this.#getMovesPawn(row, col, validMoves);
if (spot.charAt(1) === "N") this.#getMovesKnight(row, col, validMoves);
if (spot.charAt(1) === "B") this.#getMovesBishoop(row, col, validMoves);
if (spot.charAt(1) === "R") this.#getMovesRook(row, col, validMoves);
if (spot.charAt(1) === "Q") this.#getMovesQueen(row, col, validMoves);
首先,我嘗試嘗試將所有功能放在一個物件中
this.moveFunctions = {"P": this.#getMovesBishoop, "B": this.#getMovesBishoop, "N": this.#getMovesKnight,"Q":this.#getMovesQueen, "R": this.#getMovesRook}
// then executing them
this.moveFunctions["P"](0, 0, []);
但是這樣做時,this變數會從所有資訊所在的 Class 變數更改為僅包含函式
// from this
{
"apple": 1,
"pear": 2
...
}
// to
{"P": this.#getMovesBishoop, "B": this.#getMovesBishoop, "N": this.#getMovesKnight,"Q":this.#getMovesQueen, "R": this.#getMovesRook}
我的問題是我如何設法使this.moveFunctions作業或更好的東西?我已經搜索了 stackoverflow 和谷歌,但我也沒有嘗試在 python 中嘗試這個并且它有效
uj5u.com熱心網友回復:
您忘記系結正確的this- 請參閱“this”關鍵字如何作業?.
當你寫a.b()這不同于const x = a.b; x()因為a.b()自動傳遞給方法a的語法。當您這樣做時,這種自動“連接”就會丟失,因為它僅在您執行緊接在屬性訪問之前的函式呼叫時才會發生,但這里屬性訪問和函式呼叫發生在兩個不同的地方。thisa.bx()
您觀察到的行為是因為這里有一個到物件的自動“連接”,但它不是您期望的物件,因為["P"]它也是一個屬性訪問(就像.P)所以現在您有另一種a.b()情況,但是a存在this.moveFunctions!
這兩種情況的解決方案(在呼叫之前根本沒有屬性訪問或對不需要的物件的屬性訪問)是bind正確this的函式(const x = a.b.bind(a); x()有效)或使用call傳遞它(const x = a.b; x.call(a)也有效)。
在您的情況下,call可能是更簡單的方法:
this.moveFunctions["P"].call(this, 0, 0, []);
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/463620.html
標籤:javascript 节点.js 功能 班级 目的
