首页 > 解决方案 > 理解 call() 函数和对象

问题描述

我有一个模块化的 JS 项目,我需要对其进行调整。它使用原型继承而不是类。这是有问题的代码:

hgManager.js 中的构造函数:

export function HGManager() {
    this.USER_ID = getURLParameter( "usr" ),
    this.GAME_ID = getURLParameter( "game" )
};

hgManager.js 中的 getData():

getData: function(a, b) {
        var c = this.API + "records/" + this.USER_ID + "/" + this.GAME_ID;
        this.xhrLoad( "GET", c, a, b )
    },

hgManager.js 中的 xhrLoad():

xhrLoad: function(a, b, c, d, e) {

        var f = new XMLHttpRequest;
        f.open(a, b, true), 
        e && f.setRequestHeader("Content-type", "application/json");

        var g = this;

        f.onload = function() {
            if (4 == f.readyState && f.status >= 400 && f.status <= 599) {                     return d.call(g, f);
            }

            else { 
                var a = JSON.parse( f.responseText ).response;

                return c.call(g, a, f)    
            }

        },

        f.onerror = function() {
            return d.call(g, f)
        },


        e ? f.send( JSON.stringify( e ) ) : f.send() 
    }

调用 hgManager.getData() 的函数:

loadPlayerData: function() { 
        var a = this;
        this.game.hgManager.getData(
            function( c ) { //param 1
                if ( null === c ) { 
                    return void console.log( "DataManager: Invalid response." ); //if there is no playerData
                }

                var d = JSON.parse( c.record );
                void 0 === d || null === d || void 0 === d.selectedCharacter ? (console.log("DataManager: No data on backend, looking for data on local storage."), d = a._getLocalStorageData(), null !== d ? (console.log("DataManager: Data on localstorage found. Saving this to backend."), a.game.playerData = d) : console.log("DataManager: No data on localstorage. Saving default data to backend."), a.savePlayerData()) : console.log("DataManager: Data loaded from backend.");
                var e = new Date,
                    f = e.getFullYear() + "-" + e.getMonth();
                d.lastMonthPlayed != f && (d.lastMonthPlayed = f, d.loyaltyPoints = [], console.log("DataManager: New month, reset loyalty points.")),
                a.game.playerData = d,
                a.game.hasShownLoyaltyMessage = a.game.playerData.loyaltyPoints.length > 0,
                a.game.hasShownPortalMessage = 9 == a.game.playerData.portalPieces.length
            },

            function() { //param 2
                console.log("DataManager: Error loading user data"), 
                data = a._getLocalStorageData(), 
                null !== data ? (console.log("DataManager: Data on localstorage found."), a.game.playerData = data) : console.log("DataManager: No data on localstorage.") 
            }
        ) 
    },

让我失望的代码是return c.call(g, a, f)in xhrLoad(),以及对应的第一个参数函数loadPlayerData().

标签: javascriptxmlhttprequestprototype

解决方案


处理变量非常困难,a, b, c尤其是当它们在不同范围内表示不同的事物时。

但是让我们尝试跟随代码并重命名 args 以添加一些感觉:

xhrLoad: function(method, target, callbackSuccess, callbackError, e/* idk what is it*/) {}

getData: function(callbackSuccess, callbackError) {
        var target = this.API + "records/" + this.USER_ID + "/" + this.GAME_ID;
        this.xhrLoad( "GET", target, callbackSuccess, callbackError )
    },

this.game.hgManager.getData(
        function( response ) { //param 1 callbackSucess
                if ( null === response ) { 
                    return void console.log( "DataManager: Invalid response." ); //if there is no playerData
                }


            },
        function() { //param 2 callbackError
          //
        }

现在更容易理解了。

getData()接受两个回调函数作为参数 - 一个用于成功响应,一个用于错误。第一个必须接受响应作​​为参数。它是您的c来源this.game.hgManager.getData(function( c ) {,并在此处定义。由于它是函数的参数,因此无需在全局范围内定义它。

而且似乎与这里的课程无关。这都是关于将函数作为参数传递的。


推荐阅读