规范问题如果在用箭头函数替换函数声明/表达式后发现有关问题的问题,请将其作为此副本的副本关闭.
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) 在ES6中,这两个都是合法的:
var chopper = {
owner: 'Zed',
getOwner: function() { return this.owner; }
};
Run Code Online (Sandbox Code Playgroud)
并且,作为速记:
var chopper = {
owner: 'Zed',
getOwner() { return this.owner; }
}
Run Code Online (Sandbox Code Playgroud)
是否可以使用新的箭头功能?在尝试类似的东西
var chopper = {
owner: 'John',
getOwner: () => { return this.owner; }
};
Run Code Online (Sandbox Code Playgroud)
要么
var chopper = {
owner: 'John',
getOwner: () => (this.owner)
};
Run Code Online (Sandbox Code Playgroud)
我收到一条错误消息,提示该方法无权访问this.这只是一个语法问题,还是你不能在ES6对象中使用fat-pipe方法?