function $(x) {
return document.getElementById(x);
}
function test(x) {
alert(x.id);
}
function init() {
var o = {};
o.id = "a";
$("one").addEventListener("click", function () {test(o);});
o.id = "b";
$("two").addEventListener("click", function () {test(o);});
o.id = "c";
$("three").addEventListener("click", function () {test(o);});
}
window.onload = init;
I have some code similar to this. When the HTML elements with id's "one", "two", or "three" are clicked, they all alert "c", but I want them to alert the respective values (a, b, and c).
How can I pass the object by value and not by reference? I guess in this simple example you would just define two more objects, but my code is actually within a for-loop. The object properties are changed each iteration (ideally each iteration creates a new object) and then passed to the function.
Your object 'o' persists in the closure, so its last-assigned value is always read.
One way could be to do this:
Code:
function init()
{
var t = [ 'a', 'b', 'c' ];
$("one").addEventListener("click", function () {test( t[0] );});
$("two").addEventListener("click", function () {test( t[1] );});
$("three").addEventListener("click", function () {test( t[2] );});
}
Thanks Logic Ali. I guess I simplified my example a bit too much though, or wasn't clear enough. The function test takes an object as a parameter, not just a simple string.