3

在 JavaScript 中,如果我创建一个函数表达式,如:

var foo = function foo() {
  return 'Hello world!';
}

这个可以吗?会不会出现什么问题?或者我应该这样做:

var foo = function baz() {
  return 'Hello world!';
}
4

2 回答 2

4

The main difference is that in your first example, when inside the function, foo is a shadowed variable, and doesn't refer to the global foo. For example:

var foo = function foo() {
 foo = 1;
}
foo();
console.log(typeof(foo));

outputs 'function' because we have only redefined foo inside the function.

However if you defined the function the second way, foo refers to the global object:

var foo = function baz() {
 foo = 1;
}
foo();
console.log(typeof(foo));

And this will output 'number' since we have modified the global object.

于 2017-05-16T01:13:53.413 回答
2

这取决于你想要什么。内部名称是函数的本地名称;外部名称在外部范围内,并被闭包捕获。因此,如果您以不同的方式命名函数,则可以从内部重新分配外部引用:

var foo = function baz() {
  return foo;
};
var quux = foo;
foo = 17;
quux(); // => 17

当您将函数命名为相同时,这是不可能的,因为外部变量将无法访问,被内部变量所掩盖。如果您想要这种情况,那么您将需要以不同的方式命名它们。但是,我不会说以任何一种方式命名函数有任何问题

编辑:除非您需要支持报废的浏览器。然后小心龙。

于 2017-05-16T00:42:07.940 回答