Question

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

Was it helpful?

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.

OTHER TIPS

In this particular instance:

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

The browser will throw an error because function is a reserved keyword.

Given a different variable name, then you are just assigning a value to a (global) variable. The variable will be overwritten with a new (identical) function with each successive execution of the widget script.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top