简体   繁体   中英

Can I use an object in function's parameter in javascript?

I need to use:

var obj=document.getElementsByClassName[n];
setInterval("somefunc("+obj+");",10);

When I'm trying to run this code, I get "Uncaught SyntaxError: Unexpected identifier". I know about this problem with setTimeout("alert("+str+");) , when I should use .toString() , but what if I need to pass an object in function?

Thank you.

Yes you can but like this:

setInterval(function(){
   somefunc(obj);
},10);

So here is how your code should be:

var obj = document.getElementsByClassName(n);
setInterval(function(){
   somefunc(obj);
},10);

You had these problems with your previous code:

  • You were calling your function immediately by passing param eg someFun(obj)
  • You were using eval() function behind the scenes by wrapping your code in quotes.
setInterval(function () { somefunc(obj) }, 10);

you can use it like

var obj=document.getElementsByClassName[n];
setInterval(function() {return somefunc(obj)},10);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM