ES6箭头函数(arrow function)
来源:互联网 发布:幸福狐狸淘宝是真的吗 编辑:程序博客网 时间:2024/04/30 00:12
ES6的箭头函数对this
关键字的绑定的改进老生常谈了。不再赘述,这里仅仅尝试一下改进的甜头。
下面片段对比了实用arrow function和不使用的区别:
class Person { constructor(firstname, lastname) { this.firstname = firstname; this.lastname = lastname; } getName() { setTimeout(() => { console.log(this.firstname, this.lastname); }, 1000); } getNameV2() { setTimeout(function() { console.log(this.firstname, this.lastname); }, 1000); }}var p = new Person('jianyong', 'lee');p.getName(); // jianyong leep.getNameV2(); // undefined undefined
注意到p.getNameV2()
没有正确输出,“衬托”出了arrow function的“强大”。
那么在ES5中以及之前的js版本中,如何处理这个情况呢?老一辈的jser能工巧匠实用下面方法解决:
1. 使用bind函数
getNameV3() { setTimeout(function() { console.log(this.firstname, this.lastname); }.bind(this), 1000); }
- 保存
this
引用
getNameV3() { var ctx = this; setTimeout(function() { console.log(ctx.firstname, ctx.lastname); }.bind(this), 1000); }
0 0
- ES6箭头函数(arrow function)
- ES6之箭头函数(Arrow Function)
- JavaScript-ES6中的箭头函数(Arrow Function)
- ES6新特性箭头函数(Arrow Function)
- 【ES6】之 Arrow Function箭头函数
- ES6箭头函数(Arrow Functions)
- ES6箭头函数(Arrow Functions)
- ES6箭头函数(Arrow Functions)
- ES6折腾记- 箭头函数【Arrow function】要点及脱坑点
- ES6:箭头函数 Arrow Functions
- 深入浅出ES6(七):箭头函数 Arrow Functions
- 深入浅出ES6(七):箭头函数 Arrow Functions =>
- 深入浅出ES6(七):箭头函数 Arrow Functions
- 深入浅出ES6(七):箭头函数 Arrow Functions
- 深入浅出ES6:箭头函数 Arrow Functions
- es6之Arrow Function
- es6 的arrow function
- es6的箭头函数,function* , yeild详解
- 安装和使用Inforbright
- iOS--tableview单元格重用(单元格上创建控件情况下)
- 未能找到类型或命名空间名称“*”(是否缺少 using 指令或程序集引用?) 异常的解决
- 在Android环境中使用Valgrind工具进行内存错误检测
- c++感悟
- ES6箭头函数(arrow function)
- 循环结构中break和continue的替代方法(Repetition without break and continue statement)
- Git : Ubuntu-git服务器搭建之亲自搭建
- popupwindow相关知识
- 取对象的Key和值
- 实例化一个新控件-html
- java 通过Httpclient模拟https Post 请求,实现双向认证
- 完成端口(I/O completion)原理
- 1009 Problem I