Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a random method name

I plan on using JSONP to call an external web service to get around the fact that I don't want to create a global function that could potentially conflict with the calling page. I thought that creating a random function name and passing it up would work. Something like this:

<script src="www.foo.com/b?cb=d357534">

where cb is the callback function name, the server would return

d357534({my json data});

What I want to know is how to create the random function name, I'm sure I could use eval but is this the best way to go about it?

Essentially, what I am trying to do is this:

var d + Math.floor(Math.random()*1000001) = function(){...   
like image 789
Russ Bradberry Avatar asked Mar 06 '26 23:03

Russ Bradberry


2 Answers

This should do what you want. You need to save the function name somewhere so that you can pass it to the server, but you can do that inside of a local scope to avoid polluting your global namespace.

var functionName = 'd' + Math.floor(Math.random()*1000001);
window[functionName] = function() { ... }
like image 184
Brian Campbell Avatar answered Mar 09 '26 12:03

Brian Campbell


To make a randomly-named global variable you could do this:

window['randomvar' + Math.floor(Math.random()*1000001)] = function() { ... };

now of course you've got the problem of remembering the random name somewhere. You could make up a random name for that variable too. Then you'd have to remember the name of that variable, so that you could look at its value and then know how to find your function. After a while, things are going to start getting weird.

like image 33
Pointy Avatar answered Mar 09 '26 12:03

Pointy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!