I'm trying to access a function through the window object. In my code, my function gets referred to by a string so I have to use the window object (or eval) to grab it. I tested out my code in pure JavaScript and it works perfectly. But when using jQuery it fails. Here is my test code:
function speak(words, callback){
for(var i=0;i<10000;i++){
console.log(words);
}
if(callback)
callback.call();
}
console.log(window['speak']);
Here is a link to the pure JavaScript version which works.
Here is a link to the jQuery version which doesn't work.
What do I need to do to make this work in jQuery?
You didn't declare speak
as a member of window
, and JSFiddle actually wraps it in a document.ready
callback. You'll need to explicitly set window.speak = speak
as part of your code if you want it available on the window
object.
Alternatively, you need to configure your fiddle to execute without a wrapper rather than onDomReady