跳到主要内容

箭头函数

  • 箭头函数是一个语法糖,它允许我们用更简洁的语法来写函数。

1. 0个参数

let noParams = () => logd("Hello, world!");
noParams(); // 输出 "Hello, world!"

2. 1个参数

  • 如果只有一个参数,可以省略括号
let singleParam = x => logd(x);
singleParam("Hello"); // 输出 "Hello"

3. 多个参数

let multipleParams = (x, y) => logd(x + y);
multipleParams(1, 2); // 输出 3

4. this绑定

  • 箭头函数没有自己的this绑定,它将this绑定到其外部函数的this
let obj = {
value: "outer",
method() {
let arrowFunc = () => logd(this.value);
arrowFunc(); // 输出 "outer"
}
};
obj.method();

5. 三目运算符

let func = x => x > 0 ? 'positive' : 'negative';
logd(func(1)); // 输出 "positive"
logd(func(-1)); // 输出 "negative"