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

岁酱吖の 提交于 2019-12-01 06:28:31

问题


Take a test:

<script>
    function say() { alert( "ABOVE" ); }

    say();

    function say() { alert( "BELOW" ); }
</script>
  • The result is "BELOW" for all test (Chrome, Firefox, IE).
  • How does javascript interpreter work in this case?
  • http://jsfiddle.net/jcv6l/ << run the code.

回答1:


Basically, because of hoisting, which pulls all function declarations to the top of the current scope, the interpreter is basically doing this:

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

That is why it always ends up alerting below




回答2:


In this case the interpreter parses the function definitions first and the last function definition wins.

This question has also been answered at: Ambiguous function declaration in Javascript

There is also a good article here: http://kangax.github.com/nfe/




回答3:


(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();

}())

Output:

sing2
string string
sing2



回答4:


The interpreter first reads all declarations of the functions, then executes the other statements that are outside functions. So the latter declaration overrides the former, which is why the latter was called.




回答5:


It's because the latter function overwrites the previous one. If you try to log the function:

console.log(say);

It will return only:

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

The "ABOVE" alert has been replaced with the "BELOW" alert. Similar to declaring a variable with the same name twice in the same scope - the latter would overwrite the former.

JSFiddle example.

Why? See http://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html




回答6:


function xyz() { .. } blocks are defined at parse time. If many functions have the same name, it's the last defined which takes the precedence.


However, you can define functions at runtime using statements :

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

will output ABOVE. (JSFiddle)



来源:https://stackoverflow.com/questions/15810249/which-and-how-javascript-function-will-be-called-if-we-have-2-function-declarati

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!