简体   繁体   English

将函数分配给javascript中的全局变量

[英]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() .我想将函数test()分配给一个全局变量,以便我应该能够使用window.newName()从脚本中的其他地方调用该函数。 How can I assign this?我怎样才能分配这个?

I tried window.newName = test();我试过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.当使用window.newName = test()您实际上是在激活函数,这样,变量将获得从函数返回的值(如果有),而不是对函数的引用。

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 .当您执行window.newName = test() ,它的真正含义是“调用test ,并将其返回值分配给window.newName

What you want is window.newName = test;你想要的是window.newName = test;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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