如果我们有两个同名的函数声明,javascript函数将如何调用?
which and how javascript function will be called if we have 2 function declarations with the same name?
参加考试:
<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)
相关文章:
- 从函数JavaScript返回不可变数组/对象
- 将对象传递给函数.JavaScript
- 如何定义const函数javascript(语法糖)
- 新的日期函数javascript
- TypeError:this.getAttribute不是一个函数-javascript
- 从函数javascript发送变量
- 扩展自容器函数Javascript
- 从内部函数javascript内部分配外部函数的对象
- 使用函数JavaScript中的函数
- 在这里使用回调函数(JavaScript)有什么好处吗
- 来自函数 Javascript 的 NaN 返回值 ||函数执行顺序
- 将“e”传递给一个新函数 - javascript
- 调用函数中的一个函数——Javascript
- 传递的变量不适用于我的函数-Javascript
- 如何将类方法设置为等于多个函数?-Javascript
- 显示php中的函数javascript
- 如何使用php代码创建函数Javascript弹出框
- 未调用的外部函数-javascript
- 如何在类中运行函数.Javascript
- 关闭mouseover上的一个函数——Javascript,jQuery