qwertyuiop
01-05-2012, 06:16 AM
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.
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.