如果箭头表达式仅仅就是简化了函数的命名,我们为什么要改变原来的习惯而去使用它呢?所以我们需要了解一下箭头函数的特性

箭头函数内部没有constructor方法,也没有prototype,所以不支持new操作。但是它对this的处理与一般的普通函数不一样。箭头函数的 this 始终指向函数定义时的 this,而非执行时。我们通过一个例子来理解:

var o = {
x : ,
func : function() { console.log(this.x) },
test : function() {
setTimeout(function() {
this.func();
}, );
}
}; o.test(); // TypeError : this.func is not a function

上面的代码会出现错误,因为this的指向从o变为了全局(函数调用中的this都是指向全局的)。

我们需要修改上面的代码如下:

var o = {
x : ,
func : function() { console.log(this.x) },
test : function() {
var _this = this;
setTimeout(function() {
_this.func();
}, );
}
}; o.test();

通过使用外部事先保存的this就行了。这里就可以利用到箭头函数了,我们刚才说过,箭头函数的 this 始终指向函数定义时的 this,而非执行时。所以我们将上面的代码修改如下:

var o = {
x : ,
func : function() { console.log(this.x) },
test : function() {
setTimeout(() => { this.func() }, );
}
}; o.test();

这回this就指向o了。

我们还需要注意一点的就是这个this是不会改变指向对象的,我们知道call和apply可以改变this的指向,但是在箭头函数中是无效的。

var x = ,
o = {
x : ,
test : () => this.x
}; o.test(); //
o.test.call(o); // 依然是1

最新文章

  1. 8.Java格式化输出
  2. iOS开发 iOS10兼容访问http
  3. javascript 网络是否连接的几种方案
  4. ftp服务器测试
  5. WPF的数据绑定详细介绍
  6. struts2中使用ognl表达式时各种符号的使用规则$,#,%
  7. PHP:基于百度大脑api实现OCR文字识别
  8. AngularJS高级程序设计读书笔记 -- 大纲篇
  9. Tomcat7以上403 Access Denied错误
  10. redhat下yum命令安装(替换为centos yum命令)
  11. 重读 必须知道的.NET
  12. Python发送邮件脚本
  13. spark streaming中维护kafka偏移量到外部介质
  14. Hillstone防火墙sslvpn配置与使用
  15. nodejs 中的一些方法
  16. This Debug perspective is designed to support application debugging.it incorporates views for displaying the debug stack,variables and breakpoint mamagement
  17. 【代码笔记】Web-ionic tab(选项卡)
  18. [Android实例教程] 教你如何拍照+相册选择图片+剪裁图片完整实现
  19. windows下vue开发环境的搭建
  20. ajax请求跨域

热门文章

  1. hdu多校1004 Distinct Values
  2. Lexicography
  3. ftp主动模式与被动模式交互过程分析
  4. 使用web3+solc编译发布以太坊智能合约
  5. html <iframe>介绍
  6. WPF 基于Adorner实现类似Popup效果
  7. Oracle 12c新特性
  8. 反片语 UVA 156
  9. NIO完成网络通信(一)
  10. ADO.NET 连接池 Session 状态分析