Javascript change global value

Global Variable JavaScript (Changing Value)

Solution 1: You should seriously consider changing your script to allow creation of context objects that you can use to call library functions; this will remove your dependency on global variables (which should be avoided) while also allowing two different contexts to be used on the same page . Question: I have a couple of JavaScript functions that I would like to reuse on multiple different pages, so I created an external .js file for the functions.

Global Variable JavaScript (Changing Value)

Is it possible to change the value of a global variable in JavaScript?

If so, is it possible to do it in a function called by an event listener such as «onreadyStateChange»?

It’s working for normal functions. but doesn’t change when I call a function like this:

 var dom1 = 3; function work() < . http.onreadyStateChange=handleHttpResponse; . >function handleHttpResponse() < var xd; if (http.readyState == 4) < if (http.status == 200) < if (http.responseText == "granted") < dom1 = 1; >else < dom1 = 2; >> else < alert("Error"); >> > 

You can change the value of any variable in JS, local or global. In a function, make sure you don’t declare a local variable with the same name and you can access the global. Even if you do declare a local, you can access the global as a property of window . You can change most properties as well; there are very few immutable data types in JS or the DOM.

Читайте также:  Javascript add text to iframe

If a variable isn’t being set as you expect, you can use Firefox and firebug to debug the code and observe what’s happening.

Please use window[‘dom1’] = ****; instead of var dom1 = ****;

  

You would find the global value «dom1» is finally changed!

Turn a JavaScript local variable into a global variable, You should be able to add the variable’s value to a property of the global window object: window.yourVarName = yourVarName; Then the other …

Temporarily change a JavaScript global variable

I’m trying to invisibly swap one library for another but only for a given scope. Here’s a simplified sketch of the problem. x represents the old preexisting library, y represents the new library and $ is the global I want to affect. The goal is to have withLib successfully change $ from x to y for all the code within it’s callback.

You can see with this example, I can affect the code in the outer context but not the inner. I’ve tried wrapping the callback() in a closure but that didn’t quite do it either.

x = "1.0" y = "2.0" $ = x; withLib = function(callback) < $ = y callback() $ = x >withLib(function() < console.log($, $ == "2.0" ? "outer success" : 'outer fail') someCb = function() < console.log($, $=="2.0" ? "inner success" : "inner fail") >>) someCb() // results in "outer success" and "inner fail" 

I think the answer involves setting up the right kind of closure but I can’t see how. Any thoughts?

You could use an anonymous function to create a scope where $ is y :

x = "1.0" y = "2.0" $ = x; (function ($) < console.log($, $ == "2.0" ? "outer success" : 'outer fail') someCb = function() < console.log($, $=="2.0" ? "inner success" : "inner fail") >>(y)); someCb() 

Alternatively, the keyword with is generally to be avoided, but if you’re set on it:

At the top of the function (or functions) that use the old library, you could replace the $ reference, but only in the local scope like so:

This will not affect the global values for $ , x , and y , but will only work on calls within the scope of doStuff .

x = "1.0" y = "2.0" withLib = (function(callback, $) < callback($) >) withLib(function($) < console.log($, $ == "2.0" ? "outer success" : 'outer fail') someCb = function() < console.log($, $=="2.0" ? "inner success" : "inner fail") >>, y) someCb() 

Try withLib(. x) to pass in x as the «$» library.

Temporarily change a JavaScript global variable, At the top of the function (or functions) that use the old library, you could replace the $ reference, but only in the local scope like so: function …

Is it possible to internal change global variables from external JavaScript?

I have a couple of JavaScript functions that I would like to reuse on multiple different pages, so I created an external .js file for the functions. I was wondering if it was possible to change the global variables of that javascript without changing the actual . js file . Here’s an example of what I mean:

Suppose I have this tag for my external JavaScript:

Could I somehow define the global variables for the scripts in the tag like so?

  
   

Or would I have to define them inside the actual myscripts.js file?

You should seriously consider changing your script to allow creation of context objects that you can use to call library functions; this will remove your dependency on global variables (which should be avoided) while also allowing two different contexts to be used on the same page . For example, if you have this right now:

var sampleGlobalVariable = 'default1'; var sampleGlobalVariable2 = 'default2'; function foo()

Consider doing this instead:

// Rename this function to something specific to your script, to // prevent possible name clashes. function createScriptContext(sampleGlobalVariable, sampleGlobalVariable2) < if (sampleGlobalVariable === undefined) < sampleGlobalVariable = 'default1'; >if (sampleGlobalVariable2 === undefined) < sampleGlobalVariable2 = 'default2'; >var that = <>; that.foo = function () < alert(sampleGlobalVariable); >; > 

Then you could use this function from your page to create the context that will be used by other scripts:

  

A more robust solution would take an object as an argument to the context creation function and initialize the variables from its properties; this will make your settings bound by name instead of by position, as well as making them all syntactically optional.

  

myscripts.js will have access to the global variables defined before.

Alternatively you can turn myscripts.js into a server-side script (written in PHP for example). That would let you pass parameters like this:

The server-side script would then have to read $_GET[‘foo’] and $_GET[‘bar’] and echo custom generated javascript back:

echo 'var sampleglobalvariable = ' . json_encode($_GET['foo']) . ';'; echo 'var sampleglobalvariable2 = ' . json_encode($_GET['bar']) . ';'; echo 'alert(sampleglobalvariable); // rest of the script, etc'; 

You can’t use src and have contents.

  

Javascript — Changing global variable value inside, Here is my simple scenario. I have a variable defined inside the ready() function which assigns the first value. I also have a function outside …

Источник

How can I set a Global Variable from within a function

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

Technically, if you don’t declare it, the browser will declare it globally, but this is unsafe and will not pass strict mode in the future (coming soon to a browser near you =D)

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
  • Or, declaring it as a property of the window object: window.options = ‘blah’;

Using jQuery’s Data() Method

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:

// 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.

I disagree that setting global data on the document is any better than creating a global variable. Still has all the problems of globals, plus it requires a lot more typing

I see what you’re saying, but the data method is not doing what you think. See this answer for an explanation: stackoverflow.com/questions/5905994/…

My comment has nothing to do with the implementation of $.data , you don’t know how I think $.data is implemented. The problem is that something that is associated with the whole document, suffers from the same problems as creating a global variable, everybody accessing and changing it, name collisions. The broader you scope your stuff, the more likely you are to run into problems

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

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.

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

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.

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

I don’t ever use globals, but if forced to do so, I also use window.varName or self.varName for clarity.

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:

    Make an indirect15.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. This forces the code to be run in the global execution context. 10.4.2 We can then declare 10.5 a 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) > 
var global = (function()< return this >).call(null) global[ident] = value 

Okay, more reading, for those of you who haven’t fainted from specification links and eval calls, yet:

  1. @kangax covers 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 intended to 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,
    • 10.4, Establishing an Execution Context: Covers how ‘global code’ and ‘eval code’ are handled, specifically.
    • 10.2, Lexical Environments: These describe “where variables are stored.” (The ‘Global Environment’ of interest is one of these.)
    • 10.1, Types of Executable Code: Covers what ‘global code’ and ‘Program’s are.
    • 15.1, The Global Object: Unfortunately, far less relevant than its title makes it sound. 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. 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. (= [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.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.

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 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; this, along with religious application of the var keyword, 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. (;

Источник

Оцените статью