如何在Javascript中保留回调函数的范围

时间:2014-07-08 18:54:02

标签: javascript callback scope

我有一个简单的函数,它是一个类ImageUtils的成员,它加载一个图像:

this.loadSingleImage = function( path, callbackComplete, callbackFail )
{
    var img = new Image();
    img.src = path;

    img.onload = callbackComplete;
    img.onerror = callbackFail;

    return img;
}

我试图了解如何能够在回调函数中访问回调函数范围之外的变量。我已经阅读了call()和apply(),但对于我上面的函数,没有一个对我有意义。现在回调函数的范围是ImageUtils。我需要它与我调用ImageUtils.loadSingleImage()的范围相同。


编辑以提供其他详细信息:

请考虑以下事项:

var Image_Utils = new function()
{
    this.loadSingleImage = function( path, callbackComplete, callbackFail )
    {
        var img = new Image();
        img.src = path;
        trace( '   load image: ' + path );

        img.onload = callbackComplete;
        img.onerror = callbackFail;

        return img;
    }
}

var SomeOtherClass = new function()
{
    this.init = function()
    {
        Image_Utils.loadSingleImage( 'somepath', SomeOtherClass.onImageLoaded, SomeOtherClass.onImageFailed );
    }

    this.onImageLoaded = function()
    {
        // console.log( this );
        // returns Img, not SomeOtherClass
        // why?
    }

    this.onImageFailed = function()
    {
        // console.log( this );
        // returns Img, not SomeOtherClass
        // why?
    }
}

2 个答案:

答案 0 :(得分:1)

你可以试试这个: -

this.loadSingleImage = function( path, callbackComplete, callbackFail )
  {
  var me = this,
  me.img = new Image();
  me.img.src = path;

  me.img.onload =    callbackComplete.bind(me);
  me.img.onerror = callbackFail.bind(me);

  return img;
  }

答案 1 :(得分:0)

这一切都取决于你定义函数/调用它的位置。这是一些范围的例子。我想在你的例子中你想要访问类似b变量的东西。

// Global variable
var c = "C";

// Anonymous function. Both b and myFunc are in the same scope
(function() {
   var b = "B";    
   var myFunc= function(a) {
      console.log(a); // logs A which is a parameter
      console.log(b); // logs B as this function is defined in the same scope
      console.log(c); // logs C as this is a global variable
      console.log(d); // logs undefined as it's defined in a different function scope
   };

   myFunc("A");    
})(); 

// Anonymous function. Different scope to the previous one
(function() {
   var d = "D";
})();