ecmascript5中,this指针的问题

天崩地裂金刚不坏 2016-07-07 09:43:18
有了箭头函数在ES6中, 我们就不必用that = this或 self = this 或 _this = this 或.bind(this)。例如,下面的代码用ES5就不是很优雅:

?
1
2
3
4
var _this = this;
$('.btn').click(function(event){
_this.sendData();
})
在ES6中就不需要用 _this = this:

?
1
2
3
$('.btn').click((event) =>{
this.sendData();
})
不幸的是,ES6委员会决定,以前的function的传递方式也是一个很好的方案,所以它们仍然保留了以前的功能。

下面这是一个另外的例子,我们通过call传递文本给logUpperCase() 函数在ES5中:

?
1
2
3
4
5
6
7
8
9
10
var logUpperCase = function() {
var _this = this;

this.string = this.string.toUpperCase();
return function () {
return console.log(_this.string);
}
}

logUpperCase.call({ string: 'ES6 rocks' })();
而在ES6,我们并不需要用_this浪费时间:

?
1
2
3
4
5
var logUpperCase = function() {
this.string = this.string.toUpperCase();
return () => console.log(this.string);
}
logUpperCase.call({ string: 'ES6 rocks' })();
...全文
117 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
这里边不是太懂。

87,910

社区成员

发帖
与我相关
我的任务
社区描述
Web 开发 JavaScript
社区管理员
  • JavaScript
  • 无·法
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧