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的情况使用方法如下
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:
使用bind/apply/call或用es6的箭头函数编写
参考这个链接描述