Javascript 如何从函数中设置全局变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5556699/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 17:47:28  来源:igfitidea点击:

How can I set a Global Variable from within a function

javascriptjquery

提问by Phill Pafford

How can I set a Global Variable from within a function?

如何从函数中设置全局变量?

$(document).ready(function() {
    var option = '';

    $("[name=select_option_selected]").change(function() { 
        var option = $(this).val();
        alert(option); // Example: Foo  
    });

    alert(option); // Need it to alert Foo from the above change function    
});

回答by hunter

Declare it outside the scope of your jQuery onready

在 jQuery onready 范围之外声明它

var option = '';

$(document).ready(function() {
    $("[name=select_option_selected]").change(function() { 
        option = $(this).val();
        alert(option); // Example: Foo  
    });

    alert(option); //This will never be "Foo" since option isn't set until that select list changes
});

if you want to initialize this to the current selected value try this:

如果要将其初始化为当前选定的值,请尝试以下操作:

var option = "";
var $select_option_selected = null;

$(function() {        
    $select_option_selected = $("[name='select_option_selected']")
    $select_option_selected.change(function() { 
        option = $(this).val();
    });    
    option = $select_option_selected.val();
});

回答by typeof

The Bad Way

坏方法

As the other answers point out, it's not a good ideato create global variables. And as they point out, you can create a global variable by:

正如其他答案所指出的,创建全局变量不是一个好主意。正如他们指出的那样,您可以通过以下方式创建全局变量:

  • Declaring variable outside of all functions
  • Initializing your variable without the varkeyword
  • Or, declaring it as a property of the window object: window.options = 'blah';
  • 在所有函数之外声明变量
  • 在没有var关键字的情况下初始化变量
  • 或者,将其声明为 window 对象的属性: window.options = 'blah';

Using jQuery's Data()Method

使用 jQuery 的Data()方法

But there is a better way of creating a globally accessible value using jQuery (and other libraries). In jQuery, use the data()method to store values associated with DOM elements:

但是有一种使用 jQuery(和其他库)创建全局可访问值的更好方法。在 jQuery 中,使用data()方法来存储与 DOM 元素关联的值:

// store 'blah' at document root
$(document).data('mysite.option', 'blah');

// retrieve value
alert($(document).data('mysite.option'));

Notice "mysite"... it is a good idea to namespace your data keys for the same reason it is good to namespace global variables in javascript.

请注意"mysite"... 为您的数据键命名是个好主意,原因与在 javascript 中为全局变量命名是一样的。

回答by Zirak

$(document).ready(function() {
    var option = '';

    $("[name=select_option_selected]").change(function() { 
        option = $(this).val(); //no declaration of new variable, JavaScript goes to what encloses the function
        alert(option); // Example: Foo  
    });

    alert(option); // Need it to alert Foo from the above change function    
});

回答by JaredPar

You can use the window.prefix to access a global variable from within the scope of a function

您可以使用window.前缀从函数范围内访问全局变量

window.option = ...;

回答by Matt Greer

Are you sure you want to? global variables are generally to be avoided. In the browser, windowis the global object, so if you do window.option = ..., then optionwill be available globally.

你确定你要?通常要避免使用全局变量。在浏览器中,window是全局对象,所以如果你这样做了window.option = ...,那么option将是全局可用的。

I highly recommend naming a global variable something more unique than "option", to avoid clobbering existing stuff.

我强烈建议将全局变量命名为比“选项”更独特的东西,以避免破坏现有的东西。

Another option, which I also don't recommend: leave off var

另一种选择,我也不推荐:离开 var

myvariable = 'foo';

If myvariable has never been delcared before, it will be declared as a property on window, making it global. This is generally considered to be (very) bad practice however.

如果 myvariable 以前从未被声明过,它将被声明为 window 上的一个属性,使其成为全局的。然而,这通常被认为是(非常)糟糕的做法。

回答by ELLIOTTCABLE

Two approaches not mentioned by anybody else, applicable when you: 1. don't have access to the globalLexicalEnvironment,10.2.3and 2. are trying to write code that you wish to support systems wherein a direct reference to the global object15.1(such as windowin the HTML DOM, or GLOBALin Node[1]) isn't guaranteed:

其他人没有提到的两种方法,适用于您:1. 无法访问全局LexicalEnvironment,10.2.3和 2. 正在尝试编写您希望支持其中直接引用全局对象15.1 的系统的代码(例如window在 HTML DOM 或GLOBALNode [1] 中)不能保证:

  1. Make an indirect15.1.2.1.1call to eval, by wrapping it in a superfluous PrimaryExpression, thus: (1,eval)(...)(the digit and comma operator are meaningless) … and then calling the result thereof. This forces the code to be run in the global execution context.10.4.2

    We can then declare10.5a new variable in the global lexical environment, as suggested above; or, for that matter, do anything else that we desire within that environment:

    function global_define(ident, value){
       (1,eval) ("var "+ident+"; (function(v){ "+ident+" = v })") (value) }
    
  2. To be less round-about (and, to boot, avoid the FUD-ridden evalcall), we can directly access the global object and set a property4.2on it, which will then be available as a global variable elsewhere in our code.[2]

    Instead of taking the evalapproach above and gaining access to the global object via code we've written in the global context, it turns out we can access the global object as the thisvalue10.4.3within any function that is called with null:

    var global = (function(){ return this }).call(null)
    global[ident] = value
    
  1. 对 进行15.1.2.1.1间接调用,将其包装在多余的 PrimaryExpression 中,因此:(数字和逗号运算符无意义)……然后调用其结果。这会强制代码在全局执行上下文中运行。10.4.2eval(1,eval)(...)

    然后我们可以在全局词法环境中声明10.5一个新变量,如上所述;或者,就此而言,在该环境中做我们想要的任何其他事情:

    function global_define(ident, value){
       (1,eval) ("var "+ident+"; (function(v){ "+ident+" = v })") (value) }
    
  2. 为了不那么迂回(并且,为了引导,避免FUD缠身的eval调用),我们可以直接访问全局对象并在其上设置属性4.2,然后该属性将在我们代码的其他地方作为全局变量可用。[2]

    与采用上述eval方法并通过我们在全局上下文中编写的代码获得对全局对象的访问不同,事实证明,我们可以在任何用 调用的函数中以this10.4.3 的形式访问全局对象null

    var global = (function(){ return this }).call(null)
    global[ident] = value
    

Phew.

呼。

Okay, more reading, for those of you who haven't fainted from specification links and evalcalls, yet:

好的,更多阅读,对于那些还没有因规范链接和eval调用而晕倒的人:

  1. @kangaxcovers all of the bases quite thoroughly. Seriously, read that if you have any questions I haven't answered here (including those relating to the all-important idiosyncrasies browser support!)
  2. Obviously, the relevant sections of the ECMAScript 5 specification itself, to get an idea for how things are intendedto work in an ideal world. No, really though; I know that specifications are a scary idea, but the ES (“JavaScript”) specifications are one of the easiest-to-read and most comprehensible specs I've ever seen. They're truly excellent. Of immediate note, and in no particular order,

  1. @kangax非常彻底地涵盖了所有基础。说真的,如果你有任何我没有在这里回答的问题(包括那些与最重要的特性浏览器支持有关的问题!)
  2. 很明显的是ECMAScript 5规范本身的相关章节,以获取事物是如何的想法打算工作在一个理想的世界。不,确实如此;我知道规范是一个可怕的想法,但 ES(“JavaScript”)规范是我见过的最容易阅读和最易理解的规范之一。他们真的很优秀。立即注意到,没有特别的顺序,

    • 10.4建立执行上下文:具体介绍了“全局代码”和“评估代码”的处理方式。
    • 10.2,词法环境: 这些描述了“变量的存储位置”。(感兴趣的“全球环境”就是其中之一。)
    • 10.1可执行代码的类型:涵盖了“全局代码”和“程序”是什么。
    • 15.1,全局对象: 不幸的是,它的相关性远没有它的标题听起来那么重要。还是值得一看的。


[1]: The discussion in other answers, suggesting that exportsin Node.js and other CommonJS-compliant systems is somehow related to the global object, about which this question asks, is misleading. In terms of system-design, one might be better suited to using their environment's module tools than poking around on the global object … but that's a discussion for another Stack Overflow post. (=

[1]:其他答案中的讨论表明,exports在 Node.js 和其他符合 CommonJS 标准的系统中,在某种程度上与该问题所询问的global object相关,具有误导性。在系统设计方面,一个人可能更适合使用他们环境的模块工具,而不是在全局对象上闲逛……但这是另一篇 Stack Overflow 帖子的讨论。(=

[2]: For those of you following along in the spec, it's harder to demonstrate that property-members of the global object are accessible as Identifier dereferences. Start with 10.2.1.2Object Environment Recordsand 10.2.3The Global Environmentto understand how the global object is linked to an environment, then hop on over to 18.12.3, 18.12.2,and 18.12.1in that order, collectively describing [[Get]] on the global object.

[2]:对于那些遵循规范的人来说,很难证明全局对象的属性成员可以作为标识符取消引用访问。从10.2.1.2对象环境记录10.2.3全局环境开始,了解全局对象如何链接到环境,然后按顺序跳到 18.12.3、18.12.218.12.1共同描述[[Get]] 在全局对象上

Nota bene: At no point in this elaboration did I suggest that doing either of these things was a good idea. Or, for that matter, that interacting with the global scopeat all is a good idea. Of no relation to the question at hand, but proffered to soothe my own conscience, I add that I wrap all of my owncode in a IIFEbeginning immediately at the top of the file; this, along with religious application of the varkeyword, ensures that I never interact with JavaScript's handling of the global object at all. A huge mess, avoided. You should do that. I said so. I'm smart. (;

注意事项:在本文的阐述中,我从未建议做这些事情中的任何一件是个好主意。或者,就此而言,与全局作用域交互是一个好主意。与手头的问题无关,但为了安慰我自己的良心,我补充说,我将​​我自己的所有代码都包装在一个IIFE中,该IIFE立即从文件的顶部开始;这一点,随着宗教应用var关键字,确保我从来没有互动JavaScript的处理全局对象的所有。一个巨大的混乱,避免了。你应该这样做。我是这么说的。我很聪明。(;

回答by Dark Prince

just declare a global object

只需声明一个全局对象

var obj={};
function my_function()
{
 obj['newVariable'] = 'someValue';
}

in this way i achieved global variable.

这样我就实现了全局变量。

回答by Starkers

http://jsfiddle.net/Kba5u/

http://jsfiddle.net/Kba5u/

var foo = 'bar';

function changeFooToBaz(){
   foo = 'baz';
}

// changeFooToBaz();
console.log(foo); #=> 'bar'

Now, uncomment the call to changeFooToBaz:

现在,取消对调用的注释changeFooToBaz

var foo = 'bar';

function changeFooToBaz(){
   foo = 'baz';
}

changeFooToBaz();
console.log(foo); #=> 'baz'

changeFooToBazhas indeed changed the contents of foo, a variable that was declared at a higher scope than the function.

changeFooToBaz确实更改了 的内容foo,该变量是在比函数更高的范围内声明的。