3

在没有什么之前,我是新人,我很高兴加入这个伟大的社区。问题是,我有一个名为 Character 的 JavaScript 类,如下所示:

var Character = function()

{

    // ..Some previous Properties / Methods (included one called "StareDown()")..

    // And this method:

    this.GrabDown = function()

    {
        Context.clearRect(0, 0, CanvasWidth, CanvasHeight);
        //Context.fillRect(0, 0, CanvasWidth, CanvasHeight);
        Context.drawImage(this.GrabbingDown, CharacterX, CharacterY, SpriteWidth, SpriteHeight);

        window.setTimeout
        (
            function()

            {
                // Here is where I want to call the parent class method "StareDown()", but I don't know how.                
            },
            250
        );
    }
}

所以这是我的大问题,如何通过该子匿名函数访问父方法?我整晚都在试图弄清楚,但我找不到一些有用的信息,谢谢!

4

3 回答 3

1

您需要将this父对象存储在变量中(假设您已将函数定义为this.StareDown = function () {...}

var Character = function()

{

    // ..Some previous Properties / Methods (included one called "StareDown()")..
    this.StareDown = function() {...}

    var curCharacter = this;

    this.GrabDown = function()

    {
        Context.clearRect(0, 0, CanvasWidth, CanvasHeight);
        //Context.fillRect(0, 0, CanvasWidth, CanvasHeight);
        Context.drawImage(this.GrabbingDown, CharacterX, CharacterY, SpriteWidth, SpriteHeight);

        window.setTimeout
        (
            function()

            {
                // Here is where I want to call the parent class method "StareDown()", but I don't know how.       
                curCharacter.StareDown(...);         
            },
            250
        );
    }
}
于 2012-10-04T14:44:18.350 回答
0

您可以只使用window.setTimeout(this.StareDown,250);,但请记住该方法将在全局上下文中调用(即 this 将指向window,而不是Character调用该GrabDown方法的实例。

要将函数用作对象方法:

window.setTimeout((function(that)
{
    return function()
    {
        return that.StareDown();
    }
})(this),250);

应该管用。这相当冗长,也许查看 MDN 文档callapply尤其bind可能证明有用

于 2012-10-04T14:48:59.790 回答
0

这就是我会做的:

var Character = function () {
    this.GrabDown = function () {
        setTimeout(function () {
            // call this.StareDown in here
        }.bind(this), 250);
    };
};

这是有效的,因为我们将指针绑定到传递给this的匿名对象。因此它可以像类的普通方法一样使用。FunctionExpressionsetTimeout

于 2012-10-04T15:11:19.727 回答