01.ES6箭头表达式

简介: 01.ES6箭头表达式

安装nodejs

安装vscode


1.单行箭头表达式:

//隐含省略了return
let foo = (arg1,arg2) => arg1 + arg2;
//上述表达式相当于
// let foo = function (arg1, arg2) { return arg1 + arg2; };
let result = foo(1,3)
console.log(result)

2.多行箭头表达式(函数代码有多行,必须使用{}大括号,必须写return):

let foo = (arg1, agr2) => {
    let result = arg1 + agr2
    return result;
}
let result = foo(1,3)
console.log(result)

3.无参数:

let foo = () => {}
//以上表达式相当于
let foo = function () {}

4.一个参数(无需使用()小括号):

let  foo = arg => {
    return arg*arg;
}
let result = foo(3)
console.log(result)


5 例子

let arr = [1,2,3,4,5];
console.log(arr.filter(value => value%2 == 0))
//以上代码相当于
let arr = [1, 2, 3, 4, 5];
console.log(arr.filter(function (value) { return value % 2 == 0; }));  //[2,4]返回被2整除的值


6.箭头表达式中的this关键字:


箭头函数不会创建自己的this,它只会从自己的作用域链的上一层继承this

(1)ES5方式(计时器中无法找到this)

function Foo (name) {
    this.name = name;
    setInterval(function () {
        console.log(this.name);
    },1000);
}
let foo = new Foo('莎士比亚');
//返回name is---无法找到this.name

(2)ES6方式(计时器中可以找到this)

function Foo (name) {
    this.name = name;
    setInterval(() => {
        console.log(this.name);
    },1000);
}
let foo = new Foo("莎士比亚");
//莎士比亚


箭头函数的嵌套

关于箭头函数嵌套,也称为函数柯里化

function add(a, b) {
    return a + b;
}

function add(a) {
    return function(b) {
        return a + b;
    }
}
console.log(add(4)(5)); //输出9

箭头函数柯里化

const add = (a) => (b) => a + b;
console.log(add(4)(5)); //输出9

react中的使用

类似react-redux的connect代码

const VisibleTodoList = connect(
  mapStateToProps,
  mapDispatchToProps
)(TodoList)


目录
相关文章
|
2月前
ES6之箭头函数
ES6之箭头函数
|
2月前
|
网络架构
ES6箭头函数的特性
ES6箭头函数的特性
|
2月前
|
小程序
es6学习笔记(四)箭头函数
es6学习笔记(四)箭头函数
|
4月前
Es6箭头函数
Es6箭头函数
36 0
|
4月前
|
自然语言处理 前端开发 安全
【面试题】ES6语法五之箭头函数
【面试题】ES6语法五之箭头函数
|
5月前
|
JSON JavaScript 数据格式
ES6箭头函数和模板字符串
ES6箭头函数和模板字符串
25 0
|
11月前
【ES6】 箭头函数
【ES6】 箭头函数
32 0
|
12月前
ES6定义变量与箭头函数
详解ES6定义变量与箭头函数
|
网络架构
ES6箭头函数总结
ES6箭头函数总结
ES6箭头函数总结
ES6 从入门到精通 # 05:函数之扩展运算符、箭头函数
ES6 从入门到精通 # 05:函数之扩展运算符、箭头函数
41 0
ES6 从入门到精通 # 05:函数之扩展运算符、箭头函数