用 => 写函数,比 function 更短;this 指向声明时所在的作用域。
| 以前 · function | 现在 · 箭头函数 |
|---|---|
let sum = function (a, b) {
return a + b;
};
console.log(sum(1, 2));
// 3
|
let sum = (a, b) => a + b; console.log(sum(1, 2)); // 3 |
| 以前 | 现在 |
|---|---|
let say = function () {
console.log("hello");
};
let hi = function (name) {
return "hello " + name;
};
|
let say = () => console.log("hello");
let hi = name => "hello " + name;
// 一个参数可以省括号
// 一条语句可以省 {} 和 return
|
| 以前 · function | 现在 · 箭头函数 |
|---|---|
let obj = {
name: "大喇叭",
say: function () {
setTimeout(function () {
console.log(this.name);
// undefined(this 指向 window)
}, 100);
}
};
|
let obj = {
name: "大喇叭",
say: function () {
setTimeout(() => {
console.log(this.name);
// 大喇叭(this 指向 obj)
}, 100);
}
};
|