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

StackOverflow https://stackoverflow.com/questions/15810249

Question

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.
Était-ce utile?

La solution

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

Autres conseils

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/

(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

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.

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

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)

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top