Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call parent method in a JavaScript Class

before nothing I'm new and I'm glad to join to this great community. The thing is, I have a JavaScript class called Character like this:

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

So this is my big question, How can I access a parent method through that sub anonymous function? I've been trying to figure it out the whole night but I couldn't find some helpful information, Thank's!

like image 575
Neo Avatar asked May 17 '26 03:05

Neo


1 Answers

You need to store your this object of the parent in a variable (assuming you have defined the function as 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
        );
    }
}
like image 68
Sidharth Mudgal Avatar answered May 18 '26 16:05

Sidharth Mudgal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!