admin管理员组

文章数量:1333201

I have the following javascript object, somewhat pseudocode:

{
  dateField: new Date(),
  addMinutes:function(numMinutes)
  {
     CallWebService(numMinutes, function{alert(this.dateField; });
  }
}

The problem is the scope of the callback function in CallWebService doesn't see the dateField property of the object. Is there a way I can access it? Thanks!

I have the following javascript object, somewhat pseudocode:

{
  dateField: new Date(),
  addMinutes:function(numMinutes)
  {
     CallWebService(numMinutes, function{alert(this.dateField; });
  }
}

The problem is the scope of the callback function in CallWebService doesn't see the dateField property of the object. Is there a way I can access it? Thanks!

Share Improve this question edited Jul 6, 2010 at 16:25 gblazex 50.1k12 gold badges99 silver badges92 bronze badges asked Jul 6, 2010 at 16:18 extnoobextnoob 1094 silver badges8 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 8

You need to preserve the context (the this value) of the addMinutes function.

There are several ways to achieve it, the most easy one is to simply store a reference of this on a variable, that variable will be available to the scope of the callback function, e.g.:

var obj = {
  dateField: new Date(),
  addMinutes: function(numMinutes) {
     var instance = this;
     CallWebService(numMinutes, function () {
       alert(instance.dateField);
     });
  }
};

The issue is that the callback is likely setting the scope of the callback function, if you use apply or call you can force the scope. You can do this with something like this:

{
    dateField: new Date(),
    addMinutes: function (numMinutes) {
        var self = this;
        var success = function () {
            alert(this.dateField;);
        };
        CallWebService(numMinutes, function () { success.apply(self); });
    }
}

You can access any property(i.e variable or function) of an object inside that object scope by using the dot(.) operator. So you can use like this:

var obj = { 
  dateField: new Date(), 
  addMinutes: function(numMinutes) { 
    callWebService(numMinutes, function() {
      alert(obj.dateField); 
    });
  } 
}

Here 'dateField' variable of the object 'obj' is accessible inside that object scope using the dot operator like 'obj.dateField'. I think this will help you to solve your problem, let me know if you are not clear with the code shown above.

本文标签: Javascript Nested Functions ScopeStack Overflow