javascriptfunctionjavascript-function-declaration

How do browsers handle multiple function declarations with the same name?


How do browsers handle multiple function declarations with the same name?

Specific test case is below - NOTE: I know this does not make sense to allow a server script to create more than one function declaration with the same name, but I am curious so please realize this before answering. This is purely for behavioral research.

Our CMS creates multiple instance of a single "widget" that is comprised of a

<div class="targetMeWithThis"></div>

and a

function startWidgetFunction() {
var param1 = $server.Variable1
var param2 = $server.Variable2
var param3 = $server.Variable3
}

When the server renders a page that has multiple instance of this widget on it, how does the browser decide which javascript function is used? Are there any browsers that actually create separate objects(functions) for each?

Thanks, j


Solution

  • in javascript, (almost) everything is an object, including functions. that being said, overwriting a function definition works exactly the same as overwriting a variable.

    var myFunc = function () {
        alert('1');   
    };
    
    myFunc(); // alerts '1'
    
    var myFunc = function () {
        alert('2');  
    };
    
    myFunc(); // alerts '2'
    

    http://jsfiddle.net/KgKgf/3/

    Note that declaring a variable that is already declared is not a good practice and many code quality tools (jslint, jshint, etc) will warn you about it.