I am having troubles with passing an object to a function using setTimeout;
function alertObject(obj){
alert(obj); //This is supposed to display "[object Object]"
}
function startCountdown(){
var myObj = new myClass();
setTimeout("alertObject("+ myObj +")",1000);
}
startCountdown();
When I run this, I get an error saying “unexpected identifier”. I know I can use an anonymous function like this;
setTimeout(function(){alertObject(myObj)},1000);
Instead of
setTimeout("alertObject("+ myObj +")",1000);
But the thing is I want to know why you can not pass an object using the eval() function. It works with strings…
You can’t serialise an object whilst maintaining the identity of that object. (In any language, not just JavaScript.)
'alertObject('+myObj+')'involves turning the object into a string withtoString(), resulting inalertObject([object Object])which is clearly not valid JavaScript.You can provide a
toString()implementation that returns something that is valid JavaScript, and use that to create a new object that is like the original object:but it isn’t the same object instance:
and there’s no way to get the actual original object, short of, for example, keeping a lookup of every instance of the object, and passing a key to that lookup.
Hiding code in strings sucks. This is one of the reasons you should never use
setTimeoutwith a string argument. Go with passing the the function object in.