6

I am having a function in javascript as

function add(v1,v2){

var add=v1+v2;

}

Now I am calling this function as below -

write.out(var param="1,2";);

write.out(window[add](param););

Using the above call, it's not working. What it does is it gives the complete string "1,2" as value to the first param(v1) of the function.

Its working if I call the function in following way -

write.out(var param1="1";);

write.out(var param2="2";);

write.out(window[add](param1,param2););

I want to achieve it using the first way where i can send the parameters as a comma separated string of parameters.

Can some one help me out how this can be done...

Thanks!!!

1
  • Don't you mean window.add or window['add']? Commented Nov 18, 2011 at 9:57

1 Answer 1

12

You can make usage of ECMAscripts .apply(), which calls a function and accepts an array of paramters.

window['add'].apply(null, param.split(','));

That way, we execute the add function, setting its context to null (you could also change that if you need) and pass in the two paramters. Since we need an Array, we call split() on the string before.

So basically, the above line is the same as

add(1,2);

Since you're haveing that function in the global context (window), we don't even need to write it that explicitly.

add.apply(null, param.split(','));

will just be fine.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.