jbassking10 jbassking10 - 1 month ago 6
Javascript Question

What's wrong with this simple Javascript?

window['TestPlugin'] = function(){
var helloWorld = function(){
alert('hello world');
}
}


I try calling this as:

$(document).ready(function () {
TestPlugin.hellowWorld();
}


but I get:


TestPlugin.hellowWorld is not a function

Answer

helloWorld is:

  • Not defined until you call the TestPlugin function
  • A local variable inside the function and not a property of the function object

For it to be a property you would need to define it like:

window['TestPlugin'] = function(){};
window.TestPlugin.helloWorld = function(){
    alert('hello world');
}

But since TestPlugin doesn't do anything, it doesn't make much sense for it to be a function, so you might as well just:

window['TestPlugin'] = {
    helloWorld: function(){
        alert('hello world');
    }
};

You also need to spell it correctly when you call it.

Comments