规范问题如果在用箭头函数替换函数声明/表达式后发现有关问题的问题,请将其作为此副本的副本关闭.
ES2015中的箭头功能提供了更简洁的语法.我现在可以用箭头功能替换所有函数声明/表达式吗?我需要注意什么?
例子:
构造函数
function User(name) {
this.name = name;
}
// vs
const User = name => {
this.name = name;
};
Run Code Online (Sandbox Code Playgroud)
原型方法
User.prototype.getName = function() {
return this.name;
};
// vs
User.prototype.getName = () => this.name;
Run Code Online (Sandbox Code Playgroud)
对象(文字)方法
const obj = {
getName: function() {
// ...
}
};
// vs
const obj = {
getName: () => {
// ...
}
};
Run Code Online (Sandbox Code Playgroud)
回调
setTimeout(function() {
// ...
}, 500);
// vs
setTimeout(() => {
// ...
}, …Run Code Online (Sandbox Code Playgroud) 对于此代码
var sum = () => {console.log(arguments); ... }
sum(2, 3)
Run Code Online (Sandbox Code Playgroud)
得到错误Uncaught ReferenceError: arguments is not defined.
为什么arguments没有在箭头功能中定义?
(() => console.log(arguments))(1,2,3);
// Chrome, FF, Node give "1,2,3"
// Babel gives "arguments is not defined" from parent scope
Run Code Online (Sandbox Code Playgroud)
根据Babel(以及我可以告诉TC39的初步建议),这是"无效的",因为箭头函数应该使用其父作用域作为参数.我能找到的唯一信息与此相矛盾的是一条评论说这被TC39拒绝,但我找不到任何支持这一点.
只是在这里寻找官方文档.