var obj = {
init:function(){
this.ajax();
},
name:function(){
console.log('123')
},
ajax:function(){
//var _this = this; 不要这种方法,我想要用改变this指向的方法
$.ajax({
url:'http://www.test3.com/Main/isCookie',
method:'GET',
dataType:"jsonp",
jsonp:'jsoncallback',
jsonpCallback:'vv',
success:function(){
console.log( this.name() ) //123
}
})
}
}
obj.init();
如何让我在ajax里的this指向指到obj上?
@Gemini 提供的方法方法很好哦~~
可以使用Function的bind方法来绑定context上下文
如果不支持bind方法,那么可以
简单
模拟个bind方法,没有考虑输入参数的合法性及bind返回函数的再次bind的情况
function _bind(orgFunc,context){
var aArgs = Array.prototype.slice.call(arguments, 2);
return function(){
return orgFunc.apply(context, aArgs);
}
}
使用方法如下
var obj = {
init:function(){
this.ajax();
},
name:function(){
return ‘123’;
},
ajax:function(){
//原生bind方法
/*
var successCallback=(function(){
console.log(this.name() ) //123
}).bind(this);
*/
//不支持原生方法的处理
var successCallback=_bind(function(){
console.log(this.name()); //123
},this);
$.ajax({
url:'http://www.test3.com/Main/isCookie',
method:'GET',
dataType:"jsonp",
jsonp:'jsoncallback',
jsonpCallback:'vv',
success: successCallback
})
}
}
obj.init();
使用bind/apply/call或用es6的箭头函数编写
参考这个链接描述
http://api.jquery.com/jQuery.ajax/
Context
Type: PlainObject
This object will be the context of all Ajax-related callbacks. By default, the context is an object that represents the Ajax settings used in the call ($.ajaxSettings merged with the settings passed to $.ajax). For example, specifying a DOM element as the context will make that the context for the complete callback of a request, like so:
$.ajax({
url: "test.html",
context: document.body
}).done(function() {
$( this ).addClass( "done" );
});