ES6 箭头函数--特性
2024-08-29 19:48:27
如果箭头表达式仅仅就是简化了函数的命名,我们为什么要改变原来的习惯而去使用它呢?所以我们需要了解一下箭头函数的特性。
箭头函数内部没有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
最新文章
- 8.Java格式化输出
- iOS开发 iOS10兼容访问http
- javascript 网络是否连接的几种方案
- ftp服务器测试
- WPF的数据绑定详细介绍
- struts2中使用ognl表达式时各种符号的使用规则$,#,%
- PHP:基于百度大脑api实现OCR文字识别
- AngularJS高级程序设计读书笔记 -- 大纲篇
- Tomcat7以上403 Access Denied错误
- redhat下yum命令安装(替换为centos yum命令)
- 重读 必须知道的.NET
- Python发送邮件脚本
- spark streaming中维护kafka偏移量到外部介质
- Hillstone防火墙sslvpn配置与使用
- nodejs 中的一些方法
- This Debug perspective is designed to support application debugging.it incorporates views for displaying the debug stack,variables and breakpoint mamagement
- 【代码笔记】Web-ionic tab(选项卡)
- [Android实例教程] 教你如何拍照+相册选择图片+剪裁图片完整实现
- windows下vue开发环境的搭建
- ajax请求跨域