Sparky
Sparky

Reputation: 4879

assign a function to a global variable in javascript

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

Answers (4)

freethejazz
freethejazz

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

user529758
user529758

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

Tomer
Tomer

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

Fenton
Fenton

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

Related Questions