簡體   English   中英

Javascript 在 class 方法中使用匿名 function

[英]Javascript use anonymous function inside class methods

我正在將工作代碼重構為class 我在加載一些Json並對其進行解析時遇到錯誤。 此代碼可以作為function正常工作,但不能在class method內工作。

代碼:

class MemoryCards {
    
    constructor() {
        this.gameData = [];
        this.cardData = [];

        this.currentLives = 0;
        this.levelLives = 0;
        this.level = 1;

        this.hasFlippedCard = false;
        this.lockDeck = false;
        this.firstCard, this.secondCard;
        this.trackMatches = 0;

        this.cardSelection = [];
    }

    startGame () {
        this.loadJSON(function(response) {
            this.gameData = JSON.parse(response);}, 
            'gameData.json');
    }

    loadJSON(callback, file) {   

        var xobj = new XMLHttpRequest();
        xobj.overrideMimeType("application/json");
        xobj.open('GET', `assets/data/${file}`, false);
        xobj.onreadystatechange = function () {
            if (xobj.readyState == 4 && xobj.status == "200") {
                callback(xobj.responseText);
            }
        };
        xobj.send(null);  
    }
}

錯誤:

game.js:21 Uncaught TypeError: Cannot set property 'gameData' of undefined
    at game.js:21
    at XMLHttpRequest.xobj.onreadystatechange (game.js:68)
    at MemoryCards.loadJSON (game.js:71)
    at MemoryCards.startGame (game.js:20)
    at (index):77

實施箭頭 Function

startGame () {
  this.loadJSON((response) => {
  this.gameData = JSON.parse(response);
 }, 'gameData.json');
}

為什么它有效?

這是因為this關鍵字。 this關鍵字默認是指全局 Object 函數有自己的塊 scope 但是箭頭普通函數在尋找全局 object時有不同的世界。

此代碼或普通 function正在尋找它的父 object ,即startGame function。

function(response) {
 this.gameData = JSON.parse(response);
}, 'gameData.json')

但是這個箭頭 function正在尋找最后一個父 object ,那就是MemoryCards

(response) => {
  this.gameData = JSON.parse(response);
 }, 'gameData.json')

這樣想箭頭 function正在尋找LAST scope 或{ }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM