0

I have a function, like following:

function handler(){
    // ...
}

And I called this function in other js file, like below:

if(window.handler())
   handler();

But I got following error in firebug console:

TypeError: window.handler is not a function

Anyone can help me?

Thanks !

3 Answers 3

2

You either declare your function like this:

window.handler = function() {
    // function code here 
};

if (window.handler) { // check if the function actually exist
    window.handler(); // call the function
}

or you change the if to:

if (typeof handler === 'function') {
    handler();
}
Sign up to request clarification or add additional context in comments.

Comments

1

if you want to check if a function exists, do it in this way:

if (window.alertHandler)
    alertHandler();

if (window.myFunc()) runs function first and check the return value. but if (window.myFunc) doesn't run it just check if myFunc exists in window object.

Comments

0

To invoke this function as method of the window object first you must make it a method of the window object.

function somefunction(){
   // ...
}

window.handler = somefunction;

//NOW you can reference it like that

window.handler();

As shown in another answer you can also assign an anonymous function directly.

Comments

Your Answer

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