Javascript 如何在ajax中将上下文传递到done
以下是场景:Javascript 如何在ajax中将上下文传递到done,javascript,ajax,jquery,Javascript,Ajax,Jquery,以下是场景: getSomething: function(){ var gotValue = sendAjax(); gotValue.done(function(response){ console.log(response); //How to pass context of object to call getSomethingElse //getSomethingElse(); }); }, getSomethingElse :
getSomething: function(){
var gotValue = sendAjax();
gotValue.done(function(response){
console.log(response); //How to pass context of object to call getSomethingElse
//getSomethingElse();
});
},
getSomethingElse : function(){
}
我想在ajax的done方法中调用getSomethingElse函数使用
$this=this代码>因为函数中的此
不是指对象
getSomething: function()
{
var $this = this;
var gotValue = sendAjax();
gotValue.done(function(response){
console.log(response);
$this.getSomethingElse();
});
},
getSomethingElse : function()
{
}
或者你可以使用
使用对当前上下文的引用:
getSomething: function () {
var self = this;
sendAjax().done(function (response) {
self.getSomethingElse(response);
});
// or even shorter: sendAjax().done(self.getSomethingElse);
},
getSomethingElse: function () {}
使用方法:
试试这个:
var someHelper = {
getSomething : function() {
var gotValue = sendAjax();
//keep a reference to the obj, normally "this", or "someHelper"
var self = this;
gotValue.done(function(response) {
console.log(response); //How to pass context of object to call getSomethingElse
//getSomethingElse();
//call getSomethingElse
self.getSomethingElse();
});
},
getSomethingElse : function() {
}
}
可以使用apply、call传递对象引用。如果您总是想获取某些引用调用的东西,请使用绑定可能的副本
getSomething: function () {
sendAjax().done(function (response) {
this.getSomethingElse(response);
}.bind(this));
},
getSomethingElse: function () {}
var someHelper = {
getSomething : function() {
var gotValue = sendAjax();
//keep a reference to the obj, normally "this", or "someHelper"
var self = this;
gotValue.done(function(response) {
console.log(response); //How to pass context of object to call getSomethingElse
//getSomethingElse();
//call getSomethingElse
self.getSomethingElse();
});
},
getSomethingElse : function() {
}
}