简体   繁体   English

如何在函数中设置全局变量

[英]How can I set a Global Variable from within a function

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

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

The Bad Way 坏道路

As the other answers point out, it's not a good idea to 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 var keyword 在没有var关键字的情况下初始化变量
  • Or, declaring it as a property of the window object: window.options = 'blah'; 或者,将其声明为窗口对象的属性: 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). 但是有一种更好的方法可以使用jQuery(和其他库)创建一个全局可访问的值。 In jQuery, use the data() method to store values associated with DOM elements: 在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中命名全局变量一样好。

$(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    
});

Two approaches not mentioned by anybody else, applicable when you: 1. don't have access to the global LexicalEnvironment, 10.2.3 and 2. are trying to write code that you wish to support systems wherein a direct reference to the global object 15.1 (such as window in the HTML DOM, or GLOBAL in Node [1] ) isn't guaranteed: 其他任何人都没有提到的两种方法,适用于以下情况:1。无法访问全局 LexicalEnvironment, 10.2.3和2.正在尝试编写您希望支持直接引用全局对象的系统的代码15.1 (例如HTML DOM中的window或Node [1]中的 GLOBAL )不保证:

  1. Make an indirect 15.1.2.1.1 call 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. 通过将它包装在多余的PrimaryExpression中,对eval进行间接 15.1.2.1.1调用,因此: (1,eval)(...) (数字和逗号运算符无意义)...然后调用其结果。 This forces the code to be run in the global execution context. 这会强制代码在全局执行上下文中运行。 10.4.2 10.4.2

    We can then declare 10.5 a new variable in the global lexical environment, as suggested above; 然后我们可以在全球词汇环境中声明10.5一个新变量,如上所述; 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 eval call), we can directly access the global object and set a property 4.2 on it, which will then be available as a global variable elsewhere in our code. 为了减少四舍五入(以及启动,避免FUD -ridden eval调用),我们可以直接访问全局对象并在其上设置属性 4.2 ,然后它将作为代码中其他地方的全局变量提供。 [2] [2]

    Instead of taking the eval approach 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 this value 10.4.3 within any function that is called with null : 我们不是采用上面的eval方法并通过我们在全局上下文中编写的代码获得对全局对象的访问,而是发现我们可以在使用null调用的任何函数中访问全局对象作为this10.4.3

     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 eval calls, yet: 好的,对于那些没有从规范链接和eval调用中晕倒的人来说,还有更多阅读:

  1. @kangax covers all of the bases quite thoroughly . @kangax 非常彻底地涵盖了所有的基础。 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 intended to work in an ideal world. 很明显的是ECMAScript 5规范本身的相关章节,以获取事情是如何打算在一个理想的世界里工作的想法。 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. 我知道规格是一个可怕的想法,但ES(“JavaScript”)规范是我见过的最容易阅读和最易理解的规范之一。 They're truly excellent. 他们真的很棒。 Of immediate note, and in no particular order, 值得注意的是,并没有特别的顺序,

    • 10.4 , Establishing an Execution Context : Covers how 'global code' and 'eval code' are handled, specifically. 10.4建立执行上下文 :具体说明如何处理“全局代码”和“评估代码”。
    • 10.2 , Lexical Environments : These describe “where variables are stored.” (The 'Global Environment' of interest is one of these.) 10.2词汇环境 :这些描述“存储变量的地方。”(感兴趣的“全球环境”就是其中之一。)
    • 10.1 , Types of Executable Code : Covers what 'global code' and 'Program's are. 10.1可执行代码的类型 :涵盖“全局代码”和“程序”。
    • 15.1 , The Global Object : Unfortunately, far less relevant than its title makes it sound. 15.1全球对象 :遗憾的是,与其标题相比,它的相关性要差得多。 Still worth a skim. 值得一试。

[1]: The discussion in other answers, suggesting that exports in Node.js and other CommonJS-compliant systems is somehow related to the global object , about which this question asks, is misleading. [1]:在其他答案中的讨论,表明Node.js和其他CommonJS兼容系统中的exports在某种程度上与全局对象有关,这个问题要求误导。 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. 在系统设计方面,人们可能更适合使用他们的环境模块工具,而不是在全局对象上徘徊......但这是对另一个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. [2]:对于那些跟随规范的人来说,更难以证明全局对象的属性成员可以作为Identifier dereferences访问。 Start with 10.2.1.2 Object Environment Records and 10.2.3 The Global Environment to understand how the global object is linked to an environment, then hop on over to 18.12.3, 18.12.2, and 18.12.1 in that order, collectively describing [[Get]] on the global object . 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 . Nota bene :在这个细节中,我没有提出过做这些事情中的任何一个都是个好主意 Or, for that matter, that interacting with the global scope at 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 own code in a IIFE beginning immediately at the top of the file; 与手头的问题没有任何关系,但是为了抚慰自己的良心,我补充一点,我将所有自己的代码包装在文件顶部的IIFE开头; this, along with religious application of the var keyword, ensures that I never interact with JavaScript's handling of the global object at all . 这一点,与宗教应用程序一起var关键字,确保我从来没有与JavaScript的处理全局对象的所有交互。 A huge mess, avoided. 一个巨大的混乱,避免。 You should do that. 你应该这样做。 I said so. 我是这么说的。 I'm smart. 我很聪明。 (; (;

Are you sure you want to? 你确定你要? global variables are generally to be avoided. 通常要避免全局变量。 In the browser, window is the global object, so if you do window.option = ... , then option will 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. 如果myvariable之前从未进行过delcared,它将被声明为窗口上的属性,使其成为全局变量。 This is generally considered to be (very) bad practice however. 然而,这通常被认为是(非常)不好的做法。

You can use the window. 你可以使用window. prefix to access a global variable from within the scope of a function 用于从函数范围内访问全局变量的前缀

window.option = ...;

just declare a global object 只是声明一个全局对象

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

in this way i achieved global variable. 通过这种方式,我实现了全局变量。

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'

changeFooToBaz has indeed changed the contents of foo , a variable that was declared at a higher scope than the function. changeFooToBaz确实改变了foo的内容, foo是一个在比函数更高的范围内声明的变量。

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

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