我有一个对象,它有几个方法,看起来像这样:
var obj = {
method1: function(){
$.get('/echo/json/', this.method2)
},
method2: function(){
var $this = this;
$.getJSON('/echo/json/', function(){
$this.method3()
})
},
method3: function(){
}
}
obj.method1();
当我调用对象的第一个方法时,我得到了这个错误(http://jsfiddle.net/MicheleC/p2gsn5gm/):
Uncaught TypeError: $this.method3 is not a function
我认为在进入回调之前引用this
可以完成任务,但我肯定遗漏了一些东西。
您成功地将this
的值从method2
传递给JSON回调函数。
问题是method2
中this
的值不是您所期望的。
此处:
$.get('/echo/json/', this.method2)
您正在传递method2
函数,并且在没有对象上下文的情况下调用它。
你需要保留那里的价值。
最简单的方法是使用bind
。
$.get('/echo/json/', this.method2.bind(this))
您需要对其进行外部引用,否则它将绑定到处理程序分配给它的任何内容(由我假设的jQuery'$'处理(
var obj = (function(){
var that = {
method1: function(){
$.get('/echo/json/', this.method2)
},
method2: function(){
$.getJSON('/echo/json/', function(){
that.method3();
})
},
method3: function(){
}
};
/* Fill it out with the methods you want */
return that;
})();
现在应该如您所期望的那样运行