规范问题如果在用箭头函数替换函数声明/表达式后发现有关问题的问题,请将其作为此副本的副本关闭.
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)