在JavaScript类中调用父级方法

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
        );
    }
}

那么这是我的一个重要问题,如何通过子匿名函数访问父方法?我已经尝试了整整一晚上但是没有找到有帮助的信息。谢谢!

3个回答

1

如果您已将函数定义为this.StareDown = function() {...},则需要将父级对象的this存储在一个变量中。

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
        );
    }
}

太棒了,这是最简单的方法,只需要将我的this分配给一个名为Parent的变量,然后通过它调用方法,就像你教我的那样。非常感谢你。 - Neo

0
你可以使用 window.setTimeout(this.StareDown,250);,但请注意该方法将在全局上下文中调用(即 this 将指向 window,而不是调用 GrabDown 方法的 Character 实例)。
要将函数用作对象方法:
window.setTimeout((function(that)
{
    return function()
    {
        return that.StareDown();
    }
})(this),250);

应该可以工作。这段话有点啰嗦,也许查看 MDN 文档中的 callapply 和尤其是 bind 会更有用。


0

这是我会做的:

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

这个方法的工作原理是因为我们将 this 指针绑定到传递给 setTimeout 的匿名 FunctionExpression 上。因此,它可以像类的普通方法一样使用。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接