javascript - Get parent object within jQuery callbacks - Stack Overflow

This is my issue:var greatapp = {start : function(){$.AJAX({url : 'foo',success : function(da

This is my issue:

var greatapp = {
  start : function(){
    $.AJAX({
      url : 'foo',
      success : function(data){
        greatapp.say(data);
      }
    })
  },

  say : function(s){
    console.log(s);
  }
}

What i don't like about this example is the fact that i repeat my self in the success function by defining the object's name instead of just this which obviously won't work because it's in an external function.

How to only have the name greatapp one time in a JS object?

This is my issue:

var greatapp = {
  start : function(){
    $.AJAX({
      url : 'foo.',
      success : function(data){
        greatapp.say(data);
      }
    })
  },

  say : function(s){
    console.log(s);
  }
}

What i don't like about this example is the fact that i repeat my self in the success function by defining the object's name instead of just this which obviously won't work because it's in an external function.

How to only have the name greatapp one time in a JS object?

Share Improve this question asked Jan 3, 2012 at 2:18 CodeOverloadCodeOverload 48.6k56 gold badges133 silver badges223 bronze badges 1
  • See stackoverflow./questions/183702/… – Ivan Commented Jan 3, 2012 at 2:21
Add a ment  | 

1 Answer 1

Reset to default 10

A mon JavaScript idiom is to save the value of this into a variable like me or self, and use that in the callback.

This will work since the callback has access to the variables declared in the enclosing scope—in other words the callback will form a closure over self

var greatapp = {
  start : function(){
    var self = this;
    $.AJAX({
      url : 'foo.',
      success : function(data){
        self.say(data);
      }
    })
  },

  say : function(s){
    console.log(s);
  }
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744332528a4568957.html

相关推荐

  • javascript - Get parent object within jQuery callbacks - Stack Overflow

    This is my issue:var greatapp = {start : function(){$.AJAX({url : 'foo',success : function(da

    8天前
    30

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信