Skip to content Skip to sidebar Skip to footer

Is It Possible To Pass An Object To An Eval/settimeout Function?

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 st

Solution 1:

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 with toString(), resulting in alertObject([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:

functionmyClass(num) {
    this.num= num;
}
myClass.prototype.toString= function() {
    return'new myClass('+this.num+')';
};

var a= newmyClass(3);
var b= eval(''+a);     // 'new myClass(3)'alert(a.num===b.num);  // true

but it isn't the same object instance:

alert(a===b); // false

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 setTimeout with a string argument. Go with passing the the function object in.

Solution 2:

You can write it like this:

setTimeout(alertObject,1000,myObj);

or like this:

setTimeout("alertObject(myObj)",1000);

In your example myObj is serialized to "alertObject([Objecct object])" which can't run.

Solution 3:

setTimeout("alertObject("+ myObj +")",1000);

is the same as

setTimeout("alertObject("+ ..object converted tostring.. +")",1000);

that is,

setTimeout("alertObject([object Object])",1000);

while

  "alertObject([object Object])"

is not valid Javascript, hence the error message.

Solution 4:

It's because the object only exists inside the function.

The callback code in the setTimeout will be called in the global scope (i.e. window) instead of the scope of your function. As myObj is a local variable inside your function, it's not available in the global scope.

If you declare the variable in the global scope instead, it will survive when your function ends, and it will be reachable from the callback code.

Note that you should use the name of the variable in the code, not concatenate the value of the variable into the string. If you do, you end up with something like "alertObject([Objecct object])", which of course can't run.

var myObj;
functionstartCountdown(){
  myObj = newmyClass();
  setTimeout("alertObject(myObj)",1000);
}

Solution 5:

setTimeout(function() {
    alertObject(object);
}, 1000);

I think this is what you need.

Post a Comment for "Is It Possible To Pass An Object To An Eval/settimeout Function?"