我已经看到了这两种类型的代码,我想知道是否有一个偏好;使用匿名或命名函数:
function myFunc() {
this.myMethod = () => {
//..
}
}
function myFunc() {
this.myMethod = function() {
//..
}
}
取自MDN:
An arrow function expression has a shorter syntax compared to function expressions and does not bind its own this, arguments, super, or new.target. Arrow functions are always anonymous. These function expressions are best suited for non-method functions and they can not be used as constructors.
这对我们匿名来说很有意义,因为您可能希望访问 myFunc 属性而不必执行 _this = this
。另一方面,它指出匿名函数最适合非方法函数(即回调)。
最佳答案
这些并不矛盾。
It makes sense to use
anonymousarrow functions as you might want to accessinstance properties without having to domyFunc
_this = this
.
是的。不过,如果它是一个方法,您只需在函数表达式中使用 this
就可以了。
On the other hand it states
anonymous functionsfunction expressions are best suited for non-method functions (i.e. callbacks).
“非方法”是指不(总是)使用设置 this 的
关键字。函数是否存储为对象属性并不重要。object.method(…)
模式调用的函数
顺便说一句,这些要点与命名表达式和匿名表达式没有任何关系。
关于javascript - 对象方法函数: Anonymous or named?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40760642/