Reputation: 4879
I have a function like this:-
function test() {
// code here
}
I want to assign the function test()
to a global variable so that I should be able to call the function from elsewhere in the script using window.newName()
. How can I assign this?
I tried window.newName = test();
, but it didn't work. Please advice.
Upvotes: 2
Views: 369
Reputation: 2285
When you do window.newName = test()
, it really means "call test
, and assign its return value to window.newName
.
What you want is window.newName = test;
Upvotes: 1
Reputation:
Don't call the variable, just assign it:
window.newName = test;
If you don't need to call it using its original name, you can use a function expression as well:
window.newName = function() {
// code here
};
Upvotes: 1
Reputation: 17930
When using window.newName = test()
you are actually activating the function and that way, the variable will get the value returned from the function (if any) and not a reference to the function.
You should do it like this:
window.newName = test;
Upvotes: 2
Reputation: 250932
You are close:
window.newName = test;
If you include the braces, as you did, it will assign the result of executing the function, rather than the function itself.
Upvotes: 3