Global variables, Javascript - javascript

Can I do this ?
var global = 0;
var truc = $.getJSON("events.json", function(json){
//alert("JSON Data: " + json[0].titre);
global = json;
});
I want to keep the contents of json and work with it outside the function.
If it was C, I would just keep the pointer but I don't know what to do with JS

yes you can do that

I don't know the details on how json works, so I cannot say what happens in your case, but this simple test works as a simplified example on how your global variable will actually work:
var global = 0;
function callTest(arr) {
//alert("JSON Data: " + json[0].titre);
global = arr;
}
var array = new Array("w", "q");
callTest(array);
alert(global);
This means that it has something to do with how json works. One thing: Are you sure the function initialized with json is actually run before you test with alert(global) ?

Related

Cant access a global variable

I am getting an undefined when I try the post to twitter function. Should the quote_text variable be global and therefore accessible by the quoteTwitter function?
$(document).ready(function () {
loadJSON();
getQuote();
console.log(quote_text);
});
// Declare variables
var json_obj;
var num = 0;
var quote_text = "";
// Display a quote - this method is not perfect since the random number will repeat itself and it appears as if no new quote is delivered
function getQuote(callback) {
var html = "";
num = randNum();
quote_text = json_obj[num].quote;
html += "<strong> " + quote_text + " </strong>";
$("#quote").html(html);
$("#author").html(json_obj[num].author);
};
// Post the current quote on twitter
function quoteTwitter(quote_text){
var tweet = quote_text;
window.open('https://twitter.com/home?status=' +encodeURIComponent(tweet),"_blank");
}
Your function definition includes quote_text as a parameter, so inside the function it's trying to use that instead of the global variable with the same name. You're presumably not passing anything to the function when you call it, so it comes out as undefined.
You can fix this by changing this:
function quoteTwitter(quote_text){
to this:
function quoteTwitter(){
...but it'd probably be better in the long run to pass the correct value in as a parameter, if possible, instead of depending on global variables.

Is it possible to provide a custom scope add remove vars to eval function?

I'm trying to use eval() to evalute a mathematical string with variables and functions
ex: algo = "1+len+customfunction(6)"
So i have data for len and the function for customFunction.
They are obviously declared in different scope.
I tried with something like
process = function(vars, algo) {
return (function() {
algo = algo.toLowerCase();
return eval(algo);
}).call(vars);
};
I need to provide required functions and variables to eval. Items are in different scopes, how do i do that ?
Now I'm a bit lost and confused, is this even possible ?
I think using eval('var'+vName+'='+value) would be ok for vars but not suitable for functions.
EDIT: btw eval can be replaced with (new Function(algo))()
http://moduscreate.com/javascript-performance-tips-tricks/
i would move the required data to an object, which hold all required items. access is possible with any given string. this solution does not requires eval()
var data = {
customfunction: function (x) {
return Math.PI * x * x;
},
len: 5
};
var variable = 'len';
if (data[variable]) {
// do something
;
}
var fn = 'customFunction';
function evaluate(vars, algo) {
if (data[algo.toLowerCase()]) { //
return data[algo.toLowerCase()].call(vars);
} else {
// fallback
}
}
var process = evaluate(vars, algo);
OK here is what i've found :
we can't provide a context for eval
eval('1+1') can be replaced by ((new Function('1+1'))() and it's way faster
eval have different scopes, can't use eval('var a = 1'); eval('alert(a)');
So, i'v managed to :
create a string to initiate all vars : vars += 'var '+key+'='+JSON.stringify(value)+';'
replace at runtime my algo string functions with their full path :
var algo = 'f(x)+5*2', x = 5;
window.object.functions.x = function(a) { return a*2; };
So at runtime i replace x( with object.functions.x(
the code executed by eval finally is eval('object.functions.x(5)+5*2'); and output is 20 of course :)
It seems to work.

Access variable from another script source

<script src="http://domain.com/source1.js"></script>
<script src="http://domain.com/source2.js"></script>
source1.js
var PICTURE_PATH = "";
var PICTURE_ROOT = base_url+"YOUTAILOR_files/";
var PROGRAM = parseInt("1");
source2.js
if(PROGRAM==3 || PROGRAM==4 || PROGRAM==5)
{
}
I could not access value of program in source2.js..
When you declare var source1Var outside a function you are actually creating a variable on the window object. So you should just be able to access it from source2.js. Just make sure source1.js is before source2.js in the script tags...
If however you're declaring it within a function, it will be private to that function. If you really need to you could set it on window explicitly.
In source1.js
function foo() {
window.source1Var = 3;
}
In source2.js
function bar() {
console.log(source1Var); // this will search window if it cannot find in the local scope.
}
What is the problem you're trying to solve? It is generally better to use some form of dependency injection, event listeners, builder pattern etc. rather than using global variables.
do something like in your first .js
var VAR = {
myvalue: "hai"
};
then call it in second like
alert(VAR.myvalue);
It's easier than you think. If variable is global, you should access it from anywhere.
// source1.js
var colorCodes = {
back : "#fff",
front : "#888",
side : "#369"
};
And in another file:
// source2.js
alert (colorCodes.back); // alerts `#fff`

Create a string (text) that declares variable and its value, for use in Javascript

I am messing with Javascript code that needs to have variable dynamic part.
I am trying to substitute this piece of Javascript code:
var data = document.getElementById('IDofSomeHiddenField').value;
var print = document.getElementById('IDofOutputField');
print.value = data;
with something like:
var encapsulatedData = "var data = document.getElementById('IDofSomeHiddenField').value;";
var encapsulatedPrint = "var print = document.getElementById('IDofOutputField');";
so that when I use somewhere in Javascript code:
encapsulatedData;
encapsulatedPrint;
this will work:
print.value = data;
But it does not work.
Is there a way how to declare:
var encapsulatedData
var encapsulatedPrint
in similar manner like I wrote above, so that:
print.value = data;
works?
Do you mean magically create global variables?
function encapsulatedData() {
window.data = document.getElementById('IDofSomeHiddenField').value;
}
function encapsulatedPrint() {
window.print = document.getElementById('IDofOutputField');
}
encapsulatedData();
encapsulatedPrint();
print.value = data;
This is not very sanitary code, and what you want is probably not what you should be doing. Could you step back and say what your goal is, rather than the means to that goal? I suspect what you really want to be using are closures or returning first-class functions for delayed evaluation.
For example:
function makePrinter(id) {
var outputfield = document.getElementById(id);
return function(value) {
outputfield.value = value;
}
}
function getValue(id) {
return document.getElementById('IDofSomeHiddenField').value;
}
var data = getValue('IDofOutputField');
var print = makePrinter('IDofOutputField');
print(data);
You have a syntax error I think. You're not closing the parentheses on the first and second lines.
var data = document.getElementById('IDofSomeHiddenField').value;
var print = document.getElementById('IDofOutputField');
print.value = data;
It is also bad form to use JS evaluation like you're attempting to do. If anything you really want to create a function for each of the page elements that returns the page element. ECMAScript 5 has properties which I think is sort of what you're looking for with what you're trying to do but that isn't how ECMAScript 3 JS can work.

How to define Global Arrays?

Code example:
<script>
var data = new Array();
data[0] = 'hi';
data[1] = 'bye';
</script>
<script>
alert(data[0]);
</script>
This gives the following error: data is not defined
How do you make something like this work? Especially if the first <script> block is being loaded on the page by ajax, and the second block is working from it. jQuery solution is acceptable.
New is not a keyword.
Use:
var data = new Array();
Or, more succinctly:
var data = [];
After your edit you mention that the first script block is loaded asynchronously. Your code will not work as written. data is a global variable, once it is loaded onto the page. You need to use a callback pattern to properly execute the code.
Since you haven't posted the asynchronous code I am not going to provide a callback sample. Though, a quick solution follows:
var interval = setInterval(function(){
if(data) {
/* ... use data ... */
clearInterval(interval);
}
}, 500);
To create a global variable, just omit 'var' from the statement. When you omit 'var', you're actually creating the variable in the window namespace.
So, zz = 1 is actually window.zz = 1
If you really wanted to, you could explicitly say
window.data = new Array(); //remember that new should be lowercase.
But you can write that faster anyway by saying
data = ['hi','bye'];
alert(data);
If you're using jQuery, perhaps you should try .getScript() rather than using .html();
// in separate file
data[0] = 'hi';
data[1] = 'bye';
// in main file
var data = [];
$.getScript(url).done(function() {
alert(data[0]);
}).fail(function() {
// handle error
});
<script>
data = [];
data[0] = 'hi';
data[1] = 'bye';
</script>
<script>
alert(data[0]);
</script>
use this, remove var makes variable global

Categories