问题描述
我写了下面的脚本来看看当一个变量和一个赋给它的函数名有冲突时会发生什么:
var f = function(){
console.log(Me original。);
}
函数f(){
console.log(Me duplicate。);
}
f();
我得到的输出是Me original。为什么没有调用另一个函数?
另外,如果我将原始赋值更改为 var f = new function(){
,我得到我原来的,后面跟着一个TypeError,说对象不是函数
。有人可以解释吗?
函数声明在JavaScript中被提升(移至顶端)。虽然在解析顺序方面不正确,但您的代码在语义上与以下内容相同,因为函数声明已被挂起:
函数f(){
console.log(Me duplicate。);
var f = function(){
console.log(Me original。);
}
f();
反过来,除了该函数的名字是相同的:
var f = function(){
console.log(Me duplicate。);
var f = function(){
console.log(Me original。);
}
f();
反过来,由于变量提升与以下情况相同:
var f;
f = function(){
console.log(Me duplicate。);
}
f = function(){
console.log(Me original。);
}
f();
这就解释了你所得到的结果,你重写了这个函数。更一般地说,JavaScript中允许多个 var
声明 - var x = 3; var x = 5
是完全合法的。在新的ECMAScript 6标准中, let
语句禁止此操作。
by @kangax在JavaScript中释放函数的功能非常出色
I wrote the following script just to see what happens when a variable and a function that has a function assigned to it have their names clash:
var f = function() {
console.log("Me original.");
}
function f() {
console.log("Me duplicate.");
}
f();
The output I'm getting is "Me original." Why was the other function not called?
Also, if I change my original assignment to var f = new function() {
, I get "Me original", followed by a TypeError saying object is not a function
. Can someone please explain?
Function declarations are hoisted (moved to the top) in JavaScript. While incorrect in terms of parsing order, the code you have is semantically the same as the following since function declarations are hoisted:
function f() {
console.log("Me duplicate.");
}
var f = function() {
console.log("Me original.");
}
f();
Which in turn, with the exception of the function's name is the same as:
var f = function() {
console.log("Me duplicate.");
}
var f = function() {
console.log("Me original.");
}
f();
Which in turn, because of variable hoisting is the same as:
var f;
f = function() {
console.log("Me duplicate.");
}
f = function() {
console.log("Me original.");
}
f();
Which explains what you're getting, you're overriding the function. More generally, multiple var
declarations are allowed in JavaScript - var x = 3; var x = 5
is perfectly legal. In the new ECMAScript 6 standard, let
statements forbid this.
This article by @kangax does a fantastic job in demystifying functions in javascript
这篇关于为什么我的JavaScript函数名称会发生冲突?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!