gpt4 book ai didi

javascript - 对象方法函数: Anonymous or named?

转载 作者:行者123 更新时间:2023-12-03 05:35:10 24 4
gpt4 key购买 nike

我已经看到了这两种类型的代码,我想知道是否有一个偏好;使用匿名或命名函数:

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 anonymous arrow functions as you might want to access myFunc instance properties without having to do _this = this.

是的。不过,如果它是一个方法,您只需在函数表达式中使用 this 就可以了。

On the other hand it states anonymous functions function 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com