我一直在看两种类型的代码,我想知道是否有偏好;使用匿名或命名函数:
function myFunc() {
this.myMethod = () => {
//..
}
}
function myFunc() {
this.myMethod = function() {
//..
}
}
摘自MDN:
与函数相比,箭头函数表达式的语法更短 表达式并不绑定它自己的this,arguments,super或 new.target。箭头功能始终是匿名的。这些功能 表达式最适合非方法函数,但它们不能 用作构造函数。
对我们来说匿名是有意义的,因为您可能想要访问myFunc属性而无需_this = this
。另一方面,它声明匿名函数最适合非方法函数(即回调)。
答案 0 :(得分:1)
这些并不矛盾。
使用
匿名箭头函数是有意义的,因为您可能希望访问实例属性而无需执行myFunc
_this = this
。
是。虽然它是一种方法,但你可以在函数表达式中使用this
,它可以工作。
另一方面,它指出
匿名函数函数表达式最适合非方法函数(即回调)。
“非方法”是指使用设置object.method(…)
关键字的this
模式(始终)调用的函数。函数是否存储与对象属性无关。
顺便说一下,这些点都与命名与匿名表达无关。
答案 1 :(得分:0)
技术上 - 没关系。
var myFunction = function() { } //anonymous
和
var myFunction = function myFunction() { } //named
在所有方面都是相同的但只有一个 - 使用调试工具并查看堆栈跟踪将显示不同的标识符。第一个版本将显示为(anonymous function)
,而后者将显示其名称 - myFunction
。因此,命名函数纯粹是为了方便开发人员和开发。
值得注意的是,函数的名称不需要与对它的引用相同,例如你可以拥有
var myFunction = function someOtherName() { /* ... */ }
然后这将在开发工具中显示为someOtherName
。但是,不可以通过执行someOtherName()
来调用它 - 名称和对函数的引用是不同的东西。为简单起见,它们通常设置为相同的标识符。
现在,在你的例子中 - 与你发布的内容不同
function myFunc() {
this.myMethod = () => {
//..
}
}
这不等同于命名函数。这是使用ES6箭头函数 - 通常,它们的名称与分配给它们的变量的名称相同:
var arrowFunction = () => {};
var obj = {
arrowMethod: () => {}
}
console.log("function name is: " + arrowFunction.name);
console.log("object property function name is: "+ obj.arrowMethod.name);
(请注意,这可以在Chrome中使用,但在某些情况下不适用于Firefox - 应该设置.name
属性)
除了命名差异之外,箭头函数还具有与“普通”函数的其他差异。最值得注意的是,他们的语境受到词汇限制。这就是实践中的意思
function arrowExample() {
this.data = "Hello arrow";
this.myMethod = () => {
return this.data;
}
}
function normalFunctionExample() {
this.data = "Hello normal function";
this.myMethod = function myMethod() {
return this.data;
}
}
var arrowInstance = new arrowExample();
var normalFunctionExampleInstance = new normalFunctionExample();
console.log("Invoking arrow with context: " + arrowInstance.myMethod());
console.log("Invoking normal function with context: " + normalFunctionExampleInstance.myMethod());
var arrowReference = arrowInstance.myMethod;
var normalFunctionReference = normalFunctionExampleInstance.myMethod;
console.log("Invoking arrow without context: " + arrowReference());
console.log("Invoking normal function without context: " + normalFunctionReference());