将函数作为参数传递时Javascript函数作用域问题

将函数作为参数传递时Javascript函数作用域问题,javascript,class,scope,Javascript,Class,Scope,如果我有以下资料: 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.can

如果我有以下资料:

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

}
您会注意到,我已将一个函数推入ScatterQuadrant函数,现在我想访问调用函数中的参数ctx。我将如何执行此操作(请参见代码中的注释)

调用这样的方法,将始终将
引用到全局对象或
未定义的
(ES5严格模式)

您需要使用
Function.prototype.call显式设置上下文,例如:

methods.call( this );
像这样调用一个方法,总是将
this
引用到全局对象或
未定义的
(ES5严格模式)

您需要使用
Function.prototype.call显式设置上下文,例如:

methods.call( this );
看看(它应该被称为“上下文”,“范围”是另一回事)。在您的情况下,使用以下各项就足够了:

methods.call(this);
看看(它应该被称为“上下文”,“范围”是另一回事)。在您的情况下,使用以下各项就足够了:

methods.call(this);

谢谢现在工作!如果允许我回答的话,我会记为正确答案。现在工作!如果允许的话,我会记为正确答案