问题说明

常见回调函数内部的this指向问题
先看下面这段代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class _Menu{
constructor(){
}
_setFollowButtonFollowed = ()=>{
console.log("austin test _setFollowButtonFollowed");
this._frame.find('.follow-btn').addClass('followed').find('span').text('已关注');
}
render = ()=>{
this._frame = $(`
<div class="menu">
<a class="follow-btn btn" href="javascript:;">
<i class="icon"></i>
<span>关注店铺</span>
</a>
</div>
`);
this._frame
// .on(touchEvent.click, ('.plan-select'), this._reportPlanSelectClick)
.on(touchEvent.click, ('.follow-btn:not(.followed)'), ()=>{
console.log('点击关注');
if (Tida.appinfo.isTaobao) {
Tida.social({
sellerId: _storeApi.sellerId,
action: 'follow'
}, function (e) {//匿名回调函数
const ret = typeof e.ret === 'object' ? e.ret[0] : e.ret;
if (ret === 'HY_SUCCESS') {
this._setFollowButtonFollowed();
}
})
}
})
在匿名回调函数中,调用了 `this._setFollowButtonFollowed()` 函数,提示的结果是

1
this._setFollowButtonFollowed is not a function
这是因为this作用域指向问题 ,success函数实际是一个闭包 , 无法直接通过 `this` 来 `_setFollowButtonFollowed` 那么需要怎么修改呢? 我们通过将当前对象赋给一个新的对象 var _this = this; 然后使用 _this 来 _setFollowButtonFollowed 就行了 完整代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class _Menu{
constructor(){
}
_setFollowButtonFollowed = ()=>{
console.log("austin test _setFollowButtonFollowed");
this._frame.find('.follow-btn').addClass('followed').find('span').text('已关注');
}
var _this = this; //修改1 重点
render = ()=>{
this._frame = $(`
<div class="menu">
<a class="follow-btn btn" href="javascript:;">
<i class="icon"></i>
<span>关注店铺</span>
</a>
</div>
`);
this._frame
// .on(touchEvent.click, ('.plan-select'), this._reportPlanSelectClick)
.on(touchEvent.click, ('.follow-btn:not(.followed)'), ()=>{
console.log('点击关注');
if (Tida.appinfo.isTaobao) {
Tida.social({
sellerId: _storeApi.sellerId,
action: 'follow'
}, function (e) {//匿名回调函数
const ret = typeof e.ret === 'object' ? e.ret[0] : e.ret;
if (ret === 'HY_SUCCESS') {
_this._setFollowButtonFollowed();//修改2 重点
}
})
}
})