which and how javascript function will be called i

2019-02-18 12:48发布

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.

6条回答
Melony?
2楼-- · 2019-02-18 13:30

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)

查看更多
Emotional °昔
3楼-- · 2019-02-18 13:32

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

查看更多
贼婆χ
4楼-- · 2019-02-18 13:33

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楼-- · 2019-02-18 13:48

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/

查看更多
兄弟一词,经得起流年.
6楼-- · 2019-02-18 13:48
(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
查看更多
Bombasti
7楼-- · 2019-02-18 13:52

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

查看更多
登录 后发表回答