简体   繁体   中英

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.

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.

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;

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
};

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM