<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`
Related
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.
I created a function to return me a jquery element.
function GetDialogButton() {
return $('a.dialog');
};
This was done as the same element was used within multiple other functions. I thought it best if it was obtained from a single place, therefore making it easier to change in future should the atribute name change.
I would like to improve this getter so that it does not perform a search everytime when called multiple times within a single page load.
How can I do this? do I cache it? or perhaps there is no need as this is optimised out?
You can create a cache variable, but it will pollute the global namespace again
var dialogButton;
function GetDialogButton() {
if(dialogButton){
return dialogButton;
}
dialogButton = $('a.dialog');
return dialogButton;
};
Creating a global cache variable is not necessary. You can do it without adding a variable to the global scope. Something like this would do:
var GetDialogButton = (function() {
var set;
return function() {
if (set === undefined) {
set = $('a.dialog');
}
return set;
};
}());
Well, you could lazy-load it.
var $dialogButton = null;
function GetDialogButton() {
if($dialogButton == null)
$dialogButton = $('a.dialog');
return $dialogButton
};
Another alternative, if you expect there to only be one dialog button you could give the element an id and then the act of searching for it will be more efficient
<a id="dialogButton">...</a>
$('#dialogButton')... // nice and quick
You could keep the global namespace clean by;
function GetDialogButton() {
if (typeof GetDialogButton.element === 'undefined' ) {
GetDialogButton.element = $("a.dialog");
}
return GetDialogButton.element;
};
I have a javascript function the initializes a bunch of global varaibles for a game.
function buildVariables(fs,fm) {
window.p1HPStart = fm.p1hp;
window.p2HPStart = fm.p2hp;
window.p1HP = 100;
window.p2HP = 100;
window.trn = 0;
}
Right now all this javascript is in the same HTML file. I want to move it to its own .js file and include it in this HTML file. I also want to replace "window" with a different global namespace like fight.p1HP.
How can I do this?
I've seen code like the below as a proposed answer in other similar questions, but I don't quite understand how it can be used to replace window.
var cartTotaler = (function () {
var total = 0; tax = 0.05;
// other code
return {
addItem : function (item) { },
removeItem : function (item) { },
calculateTitle : function () { }
};
}());
Thanks.
// initialize your own global object
if (!window.mySpace) {
window.mySpace = {};
}
// then use it
function buildVariables(fs,fm) {
mySpace.p1HPStart = fm.p1hp;
mySpace.p2HPStart = fm.p2hp;
mySpace.p1HP = 100;
mySpace.p2HP = 100;
mySpace.trn = 0;
}
Then just make sure everywhere you want one of your own variables, you use your namespace in front of it:
mySpace.variableName
Note: this doesn't really "replace" the window object (as there is no way to do that) - it just puts all your global variables into one master global object rather than pollute the global namespace with every single one of your variables.
The name mySpace can be anything you want it to be. Typically, it should be something that is unique to your application that is unlikely to conflict with something any other javascript or library might use.
(function(global){
global.p1HPStart = fm.p1hp;
global.p2HPStart = fm.p2hp;
global.p1HP = 100;
global.p2HP = 100;
global.trn = 0;
}(window));
This creates an 'immediately invoked function expression'. window is passed into the function, which then attaches a number of properties to it.
You can change window to whatever object you want, such as fight.p1HP, and this function will immediately attach the listed properties to that object.
I am relatively new to javascript and I am facing some difficulty.I have two java script files as I have shown below. I am having trouble getting the value of the variable entry_title inside the getRss function and storing it inside the variables Rss1_title and Rss2_title . Creating a global variable and assigning it to entry_title will make things worse as I will not be able to know from which Rss url the title came from. Is there a easy way to get the value of the callback functions ?
<script type="text/javascript" src="jsRss.js"></script>
<script type="text/javascript" src="notification.js"></script>
My notification.js file
function get_rss1_feeds(){
var Rss1_title = getRss("http://yofreesamples.com/category/free-coupons/feed/?type=rss");
}
function get_rss2_feeds(){
var Rss2_title = getRss("http://yofreesamples.com/category/real-freebies/feed/?type=rss");
}
setTimeout('get_rss1_feeds()',8000);
setTimeout('get_rss2_feeds()',7000);
My jsRss.js file:
function getRss(url){
if(url == null) return false;
google.load("feeds", "1");
// Our callback function, for when a feed is loaded.
function feedLoaded(result) {
if (!result.error) {
var entry = result.feed.entries[0];
var entry_title = entry.title; // need to get this value
}
}
function Load() {
// Create a feed instance that will grab feed.
var feed = new google.feeds.Feed(url);
// Calling load sends the request off. It requires a callback function.
feed.load(feedLoaded);
}
google.setOnLoadCallback(Load);
}
Errors :
When the setTimeout(get_rss1_feeds, 8000); method is called I get a blank screen.
I get a error in my console saying octal literals and octal escape sequences are deprecated and it is pointing to the 6th line in this script.
Is it because I am using google-api for parsing my Rss?
if (window['google'] != undefined && window['google']['loader'] != undefined) {
if (!window['google']['feeds']) {
window['google']['feeds'] = {};
google.feeds.Version = '1.0';
google.feeds.JSHash = '8992c0a2cdf258e5bd0f517c78243cd6';
google.feeds.LoadArgs = 'file\75feeds\46v\0751';
}
google.loader.writeLoadTag("css", google.loader.ServiceBase + "/api/feeds/1.0/8992c0a2cdf258e5bd0f517c78243cd6/default+en.css", false);
google.loader.writeLoadTag("script", google.loader.ServiceBase + "/api/feeds/1.0/8992c0a2cdf258e5bd0f517c78243cd6/default+en.I.js", false);
}
Seeing as it's a different scope, you can either return it in a callback, or provide it in another way such as exporting it to a higher scope that is visible to your desired location. In this case, it's the global scope, so I'd advise against that.
function getRss(url, callback) {
//...
function feedLoaded(result) {
if (!result.error) {
var entry = result.feed.entries[0];
var entry_title = entry.title; // need to get this value
callback && callback(entry_title);
}
}
and call it like so,
function get_rss1_feeds() {
var Rss1_title = getRss("http://yofreesamples.com/category/free-coupons/feed/?type=rss", function(entry_title) {
// This scope has access to entry_title
});
}
As an aside, use your setTimeout like so:
setTimeout(get_rss1_feeds, 8000);
rather than
setTimeout("get_rss1_feeds()", 8000);
as the latter uses eval, whereas the former passes a reference to the function.
Eventhough it will make your code a mess, you can append the variables to the window object.
For example:
function a()
{
window.testStr = "test";
}
function b()
{
alert(window.testStr);
}
Or even create your own object, instead of using window, as such:
var MyRSSReader = {
TitleOne : '',
TitleTwo : ''
}
MyRSSReader.TitleOne = "My title";
Wikipedia has a nice article about global variables, and why they are bad.
I'm writing an application in javascript and cannot figure it out how to access the variables declared in my function, inside this jquery parse. Inside I can access global variables, but I don't really want to create global vars for these values.
Basically I want to extract file names from an xml document in the simulationFiles variable. I check if the node attribute is equal with the simName and extract the two strings inside the xml elements, that part I think it's working.
How can I extract those xml elements and append them to local variables?
function CsvReader(simName) {
this.initFileName = "somepath";
this.eventsFileName = "somepath";
$(simulationFiles).find('simulation').each(function() {
if ($(this).attr("name") == simName) {
initFileName += $(this).find("init").text();
eventsFileName += $(this).find("events").text();
}
});
}
The this in the CsvReader function is not the same this in the each() callback (where instead it is the current element in the iteration). To access the scope of the outer function within the callback, we need to be able to reference it by another name, which you can define in the outer scope:
function CsvReader(simName) {
this.initFileName = "somepath";
this.eventsFileName = "somepath";
var self = this; // reference to this in current scope
$(simulationFiles).find('simulation').each(function() {
if ($(this).attr("name") == simName) {
// access the variables using self instead of this
self.initFileName += $(this).find("init").text();
self.eventsFileName += $(this).find("events").text();
}
});
}
I made a working demo (I changed it to use classes so it would work with HTML).
function CsvReader(simName) {
this.initFileName = "somepath";
this.eventsFileName = "somepath";
var context = this;
$(simulationFiles).find('simulation').each(function() {
if ($(this).attr("name") == simName) {
context.initFileName += $(this).find("init").text();
context.eventsFileName += $(this).find("events").text();
}
});
}
The simplest change you can do to make it work is... Change your function in each from normal ( function() {}) to arrow function ( () => {} ) that will automatically take the context of the function in which it is defined.