Jimmyt1988
Jimmyt1988

Reputation: 21146

Javascript function scope issues when passing function as parameter

If I have the following:

var ScatterQuadrant = function ScatterQuadrant( id, _width, _height, methods )
{
    this.id = id;
    this.canvas = document.getElementById( id );
    this.canvas.width = _width;
    this.canvas.height = _height;   
    this.ctx = this.canvas.getContext( "2d" );
    methods();

}

function Init()
{
    var scatterQuad = new ScatterQuadrant( 
        "Frame", 800, 600, function()
        {      
            this.ctx.fillStyle = "#FF0000"; // this.ctx isn't going to work, but what will?
            this.ctx.fillRect( 0, 0, 150, 75 ); 
        }
    );

}

You will notice I have pushed in a function to my ScatterQuadrant function and I now want to access the parameter ctx in the calling function. How would I go about doing this (see my comment in the code)

Upvotes: 0

Views: 197

Answers (2)

Bergi
Bergi

Reputation: 664648

Have a look at MDN's introduction to the this keyword (it rather should be called "context", "scope" is a different thing). In your case, using call() will be enough:

methods.call(this);

Upvotes: 2

jAndy
jAndy

Reputation: 236032

Calling a method just like that, will always reference this to the global object or undefined (ES5 strict mode).

You need to explicitly set the context, using Function.prototype.call for instance:

methods.call( this );

Upvotes: 2

Related Questions