繁体   English   中英

将函数作为参数传递时,JavaScript函数范围出现问题

[英]Javascript function scope issues when passing function as parameter

如果我有以下内容:

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。 我将如何执行此操作(请参见代码中的注释)

调用就这样的方法,将始终引用this 全局对象undefined (ES5严格模式)。

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

methods.call( this );

看一下MDN对this关键字的介绍 (它应该称为“上下文”,“作用域”是另一回事)。 在您的情况下,使用call()就足够了:

methods.call(this);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM