ECMAScript6箭头函数ArrowFunction"=>"
来源:互联网 发布:微信js sdk 分享 编辑:程序博客网 时间:2024/05/22 08:49
一、说明
ECMAScript6可以用箭头"=>"定义函数。x => x * x
或(x) => {return x * x;}
与匿名函数function(x){return x * x;}
相等。
二、示例
2.1 没有参数的箭头函数
var f = () => 9;console.log(f()); //9
2.2 一个参数的箭头函数
var f = x => x * x;console.log(f(3)); //9var f = x => {return x * x;};console.log(f(3)); //9var f = (x) => x * x;console.log(f(3)); //9var f = (x) => {return x * x;};console.log(f(3)); //9
2.3 两个或更多参数的箭头函数
var f = (x, y) => x * y;console.log(f(2, 3)); //6var f = (x, y , ...more) => { var multiply = x * y; for(var i = 0; i < more.length; i++){ multiply *= more[i]; } return multiply;};console.log(f(2, 3, 4, 5)); //120
2.4 map/reduce应用
var f = [1, 2, 3].map(x => x * x);console.log(f); //[1, 4, 9]var f = [1, 2, 3].reduce((x, y) => x + y);console.log(f); //6
三、this作用域/返回对象
3.1 this作用域
箭头函数中的this总是指向外层作用域,即使在内层函数里面,所以可以不用写var that = this;
。
var obj = { name: 'mazey', f: function(){ var myName = () => this.name; //这里的this指向obj return myName(); }};console.log(obj.f()); //mazey
3.2 返回对象
因为对象和块的冲突问题,箭头函数返回一个如{name:'mazey'}
的对象必需用()
括起来。
var f = () => {name:'mazey'};console.log(f()); //undefinedvar f = () => ({name:'mazey'});console.log(f()); //{name: "mazey"}
四、练习代码
<script>var f = () => 9;console.log(f()); //9var f = x => x * x;console.log(f(3)); //9var f = x => {return x * x;};console.log(f(3)); //9var f = (x) => x * x;console.log(f(3)); //9var f = (x) => {return x * x;};console.log(f(3)); //9var f = (x, y) => x * y;console.log(f(2, 3)); //6var f = (x, y , ...more) => { var multiply = x * y; for(var i = 0; i < more.length; i++){ multiply *= more[i]; } return multiply;};console.log(f(2, 3, 4, 5)); //120var f = [1, 2, 3].map(x => x * x);console.log(f); //[1, 4, 9]var f = [1, 2, 3].reduce((x, y) => x + y);console.log(f); //6var obj = { name: 'mazey', f: function(){ var myName = () => this.name; //这里的this指向obj return myName(); }};console.log(obj.f()); //mazeyvar f = () => {name:'mazey'};console.log(f()); //undefinedvar f = () => ({name:'mazey'});console.log(f()); //{name: "mazey"}</script>
ECMAScript6箭头函数ArrowFunction”=>”
阅读全文
0 0
- ECMAScript6箭头函数ArrowFunction"=>"
- ECMAScript6中的箭头函数
- ECMAScript6的新特性箭头函数
- ECMAScript6中箭头函数的用法
- ECMAScript6(ES6)标准之函数扩展特性箭头函数、Rest参数及展开操作符
- ES6箭头函数=>
- ES6-箭头函数 =>
- ES6 => 箭头函数
- ECMAScript6笔记:Generator 函数
- ECMAScript6(13):Generator 函数
- es6 的箭头函数 =>
- ES6中的箭头函数 =>
- js箭头函数 => arrow
- ES6 箭头函数(=>)
- ## 学习笔记 => 箭头函数##
- 箭头函数
- 箭头函数
- 箭头函数
- 一个经典例子让你彻彻底底理解java回调机制
- Redis AOF 持久化学习笔记
- 排高低:冒泡与插入排序。不要管别人,自己设计的才是自己的。
- Python优先级队列实现
- 17_7_17:删除一个无头单链表的非尾节点。从尾到头打印单链表
- ECMAScript6箭头函数ArrowFunction"=>"
- 机器学习_朴素贝叶斯算法识别手写数字
- 智能指针作参数
- Deepin15.4.1下CLion第一个Qt例子
- 坚持写博客,记录自己生活
- 查看Unity使用Mono版本
- DGUT oj(001)
- Codeforces 219D Choosing Capital for Treeland 树型DP
- 微信小程序入门教程--列表渲染多层嵌套循环及wx:key的使用