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
Related
<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`
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.
This is my first SO post. I'm eternally grateful for the information this community has and shares. Thanks.
I'm coming from Flash and I'm not even sure what the right question to ask is. All I can do is lay out my code example and then explain what I am trying to do. I do not fully grasp the terms that I am trying to illustrate here so I feel it is best to omit them.
The code below is incomplete as it only includes the parts that I feel are relevant to my question. Please refer to the comments in my code to see my issue.
EDIT: Full source file here: [link removed] The console.log outputs the issue in question.
<script type="text/javascript">
var a_chests = [];
var chestID = 0;
//I'm creating a plugin to be able to make multiple instances
(function ($) {
$.fn.chestPlugin = function (option) {
//This function creates a master sprite object which many of my sprites will use
//I've simplified the features to get to the heart of my question
var DHTMLSprite = function (params) {
var ident = params.ident,
var that = {
getID: function(){
return ident;
}
};
return that;
};
//ChestSprite inherits DHTMLSprites properties and then adds a few of its own
var chestSprite = function(params) {
var ident = params.ident,
that = DHTMLSprite(params);
that.reveal=function(){
console.log(ident);
};
return that;
};
//Here I create multiple instances of the chests
var treasure = function ( $drawTarget,chests) {
for (i=0;i<chests;i++){
var cs = chestSprite({
ident: "chest"+chestID
})
console.log(cs.reveal())
//This logs "chest0", "chest1", "chest2" as the for loop executes
//This behavior is correct and/or expected!
a_chests[chestID]={id:i,ob:cs};
//I add a reference to the new chestSprite for later
chestID++;
//increment the chestID;
}
console.log(a_chests[1].ob.reveal());
//This always logs "chest2" (the last chest that is created), even though
//the logs in the for loop were correct. It seems it is referencing the
//DHTML object (since the DHTMLSprite function returns that;) and since
//there is no reference to which chest I need, it passes the last one.
//Is there any way I can pass a reference to DHTMLSprite in order to retain
//the reference to the three individual chests that are created?
//Is there another solution altogether? Thanks!!!
};
//The rest of the code.
return this.each(function () {
var $drawTarget = $(this);
treasure($drawTarget,3);
});
};
})(jQuery);
</script>
You forgot to declare `that' as a local variable, so it's being overwritten on each iteration.
var chestSprite = function(params) {
var that;
var animInterval;
...
When you write:
a_chests[chestID]={id:i,ob:cs};
You are assigning the cs object itself, not an instance of this object. If later you modify cs, this will also modify what you stored in the ob property.
I guess what you need is a closure:
for (i=0;i<chests;i++){
(function(){
var cs = chestSprite({ident: "chest"+chestID});
a_chests[chestID]={id:i,ob:cs};
})();
}
This way, each loop creates a different cs object.
OK so I fixed my last error with the DIV and all..
OK so at the very top of my javascript file... I have
$(function() {
var games = new Array(); // games array
});
and then in a new function I have: var gamesLgth = games.length;
but when I run it, I get this: Uncaught ReferenceError: games is not defined
When I weird because I initalized it at the very beginning...
games is out of scope. You need to store it somewhere such that your other function can access it.
For example, this will make your variable global.
var games;
$(function() {
games = new Array(); // games array
});
$(function() {
var gamesLgth = games.length;
console.log(gamesLgth);
});
By declaring that variable within a function you have scoped the variable to that function, which means that that variable games is only available within that function.
$(function() {
var games = new Array(); // games array
...
var gamesLength = games.length; // works fine
});
But this following example will not:
$(function() {
var games = new Array(); // games array
});
$(function() {
var gamesLength = games.length; // won't work - im in a different scope
});
You initialized it as a local variable of a separate function. You need to make it global, or to pass it from function to function as argument to be able to access it.
try this;
var games = [];
instead of
var games = new Array();
and also be sure about the games scope.
I'll go ahead and write the code out for you:
var games;
$(function(){
games = new Array();
...
});
$(function(){
games.length; // Which would be zero
});
You initialized "games" in a function scope, it's not available outside the borders of $(function() { ... });
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) ?