规范问题如果在用箭头函数替换函数声明/表达式后发现有关问题的问题,请将其作为此副本的副本关闭.
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箭头函数似乎不适用于使用prototype.object将函数赋值给对象时.请考虑以下示例:
function Animal(name, type){
this.name = name;
this.type = type;
this.toString = () => `${this.name} is a ${this.type}`;
}
var myDog = new Animal('Max', 'Dog');
console.log(myDog.toString()); //Max is a Dog
Run Code Online (Sandbox Code Playgroud)
在对象定义中显式使用箭头函数,但使用带有Object.prototype语法的箭头函数不会:
function Animal2(name, type){
this.name = name;
this.type = type;
}
Animal2.prototype.toString = () => `${this.name} is a ${this.type}`;
var myPet2 = new Animal2('Noah', 'cat');
console.log(myPet2.toString()); //is a undefined
Run Code Online (Sandbox Code Playgroud)
正如概念验证一样,使用带有Object.prototype语法的Template字符串语法可以正常工作:
function Animal3(name, type){
this.name = name;
this.type = type;
}
Animal3.prototype.toString = function(){ return `${this.name} is a ${this.type}`;}
var myPet3 …Run Code Online (Sandbox Code Playgroud)