Search code examples
javascriptmethodscallparent

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!


Solution

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