如果我们有两个同名的函数声明,javascript函数将如何调用?

which and how javascript function will be called if we have 2 function declarations with the same name?

本文关键字:函数 javascript 何调用 调用 我们有 两个 如果 声明      更新时间:2023-09-26

参加考试:

<script>
    function say() { alert( "ABOVE" ); }
    say();
    function say() { alert( "BELOW" ); }
</script>
  • 所有测试(Chrome, Firefox, IE)的结果为"BELOW"。
  • 在这种情况下javascript解释器是如何工作的?
  • http://jsfiddle.net/jcv6l/& lt; & lt;

基本上,由于提升,它将所有函数声明拉到当前作用域的顶部,解释器基本上是这样做的:

function say() { alert( "ABOVE" ); }
function say() { alert( "BELOW" ); }
say();

这就是为什么它最终总是警告below

在这种情况下,解释器首先解析函数定义,最后一个函数定义胜出。

这个问题也在Javascript中有歧义的函数声明

这里也有一篇很好的文章:http://kangax.github.com/nfe/

(function () {
// even though not declared yet, every 'inner' function will be hoisted,
// and be available to the entire function
sing();
// variables are dealt with after functions, so say will be a string
// the order of declaration suggests this to be the case, but that isn't what matters
function say () { }
var say = "say";
// variables are dealt with after functions, so shout will be a string
// even though the order suggests shout should be a function
var shout = "shout";
function shout() { }
// both are functions, the latter one 'wins'
function sing() { console.log("sing1"); }
function sing() { console.log("sing2"); }
console.log(typeof say, typeof shout);
sing();
}())
输出:

sing2
string string
sing2

解释器首先读取函数的所有声明,然后执行函数外部的其他语句。因此后一个声明将覆盖前一个声明,这就是调用后一个声明的原因。

这是因为后一个函数覆盖了前一个函数。如果您尝试记录函数:

console.log(say);

它将只返回:

function say() { alert( "BELOW" ); } 

"ABOVE"警告已被"BELOW"警告所取代。类似于在同一作用域内两次声明具有相同名称的变量——后者将覆盖前者。

JSFiddle例子。

为什么?见http://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html

function xyz() { .. }块在解析时定义。如果许多函数具有相同的名称,则最后定义的函数具有优先级。


但是,您可以在运行时使用语句定义函数:
var say = function() { alert( "ABOVE" ); }
say(); 
say = function() { alert( "BELOW" ); }

将输出ABOVE。(JSFiddle)