从JavaScript中的另一个方法属性中引用对象方法属性

Refer to object method property from another method property in JavaScript

本文关键字:属性 方法 对象 引用 另一个 JavaScript      更新时间:2023-09-26

我有这种奇怪的行为,即使我可以很容易地解决它,我也想知道为什么会发生这种情况。

    function Game () {
        this.viewport = { ... };
        this.player = Player;
        this.renderer = { ... };
        this.stage = { ... };
        this.init = function () {                 
             //THIS GETS EXECUTED
             this.setKeyBindings();
        }
        this.run = function () {
             //THIS WORKS TOO
             requestAnimFrame(this.update);
        }
        this.update = function () {
             //BAD! THROWS UNDEFINED IS NOT A FUNCTION
             //HERE I NEED TO USE A REFERENCE HERE
             this.processInput();
             this.renderer.render(this.stage);
             this.handleLogic();
             //EVEN THIS ONE WON'T WORK, BUT IT WORKED IN init()!
             requestAnimFrame(this.update);
        };
        //METHODS ARE DEFINED THE SAME WAY
        this.processInput = function () {
            ...
        };
        this.handleLogic = function () {
            ...
        };
        this.setKeyBinding = function () {
            ...
        }
    }       

所以我显然错过了一些东西:

this.setKeybindings()从init方法中成功执行。

this.processInput()引发错误。

我不需要变通方法,我通过使用本地引用解决了它,比如:

        function Game () {
         var reference = this;
         .......
         this.update = function () {
             //NOW WORKS
             reference.processInput();
             reference.handleLogic();
             reference.renderer.render(reference.stage);
             requestAnimFrame(reference.update);
        }
        this.init = function () {
             //THIS ONE WORKS EVEN USING 'this'
             this.setKeyBindings()
        }
    }

我想知道为什么"this"只在某些方法(如init)中有效,而在其他方法(如update)中无效。

声明局部变量,并将this分配给它,并在任何地方使用它:

function Game () {
     var me = this;
     .......
     me.update = function () {
         me.processInput();
         me.handleLogic();
         me.renderer.render(me.stage);
         requestAnimFrame(me.update);
    }
}

这将解决引用的问题