Dynamic variables?

I want to do something that seems simple enough but I’m either looking at it wrong or not using the right terms when searching for information on it. Basically, I have local variables within some of my functions that define either a local url or a remote url. I’d like to be able to toggle this for the entire application in one place. For example:

var globalhost = localhost;

function events {
localhost = http://localhost/events.html
remotehost = http://mysite.com/events/
$http.fetch(globalhost);
}

Is this possible? Am I looking at it completely wrong or is this really insecure in some way?

Maybe I am not understanding your question correctly, but it seems that you simply your variables to have global. This is kinda default behavior for .js. so as long as you ‘var’ declare your variables at the top level of your scrip ( and do not var clare the same variable within a function /object) you should have that value available globally

As dresden_phoenix says, just declare a variable at the top level of your script and it’ll be global.
Also, there were a couple of syntax errors in the code you posted.

var globalhost = "http://localhost/events.html";

function events(){
  console.log(globalhost);
}

events();

Not insecure, but globals are seen as a bad practise because they make it very hard to follow and debug code.

I guess I could put them all as global variables (I have many functions set up like the one listed), but I’d think that the management of that would get out of hand at some point. Also, to clarify, the localhost/remotehost variables in my events function are an example and they are different in every function.

I simply would like to have one place to toggle all of my functions using their respective localhost or remotehost values in each function.

Maybe you can use bit more complicated but structured way with objects instead of raw functions. In such case every function will be represent its own “class” and you can set properties somewhere outside (in the external config).

For example:

functions.js:

function SomeHandler() {
    this.run = function() {
        console.log(this.globalHost);
    }
}

function AnotherHandler() {
    this.run = function() {
        console.log(this.localHost);
    }
}

config.js:

SomeHandler.prototype.globalHost = "http://global.host";
AnotherHandler.prototype.localHost = "http://localhost";

execution:

var s = new SomeHandler();
s.run(); // > http://global.host
var a = new AnotherHandler();
a.run(); // > http://localhost

// you can also change variable on the fly:
a.localHost = "http://newhost";
a.run(); // > http://newhost

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.