Is a function stored in memory only once? - javascript

Does javascript function stored in memory once when we define a function anywhere weather its in object or global.
function (){
alert("some value");
}
obj = {
m: function(){
alert('some value');
}
}

If you define the function one time, and pass a reference of that function to different variables/properties, then yes, it's stored one time.
var one_func = function () { console.log("I'm just one function."); };
var reused = one_func;
var reuser = { func : reused };
All of them have pointers to the same function.
But if you have something like this:
var Circle = function (r) {
var circle = {
radius : r,
calculate_area : function () { return 2 * Math.PI * r; }
};
return circle;
};
var circle_1 = Circle(2),
circle_2 = Circle(4);
The two objects do NOT share calculate_area.
You've created two distinct versions of the function.
And they must remain distinct due to function-scope and closures.
See, each copy knows about its own circle's r.
If you notice, I'm not looking at circle.radius, I'm looking at the r passed into the Circle function.
So any function which is defined inside of Circle has to be new every single time, because those functions save references to any variables inside of the constructor, through closure.
The memory-hit of having multiple copies, versus the benefits of having totally private properties is well worth it, until you hit thousands and thousands of copies (unless we're talking about gigantic objects or horrible old browsers, or running JavaScript on an LED screen on a Toaster).
More advanced engines might optimize the memory-footprint here, but it's rarely worth wasting the CPU, given how little memory each of these functions would take up, and how much RAM smartphones have (let alone custom-built gaming PCs).
EDIT
for the sake of pedantry
var Wallet = function (opening_balance) {
var balance = opening_balance,
overdraft = 50,
is_sufficient_funds = function (amount) {
return balance + overdraft >= amount;
},
deposit = function (funds) {
if (amount <= 0) { return; }
balance += funds;
},
withdraw = function (amount) {
if (amount <= 0) { return; }
if (is_sufficient_funds(amount)) {
balance -= amount;
return amount;
}
},
public_interface = {
deposit : deposit,
withdraw : withdraw
};
return public_interface;
};
Now, it should be blisteringly-apparent that we do not want balance or overdraft to be publicly accessible in any instance of Wallet.
Even this pedestrian version of Wallet is quite safe.
Sure, it's not doing any authorization right now, so you can deduct everything, or add a million dollars...
...but can you set your overdraft to $300?
Can you manually copy the value of balance?
Even if you created var wallet = Wallet(35); and then tried to rewrite the deposit method, your rewriting of it would then have absolutely no access to the private balance.
Now the closure-related benefits of this memory-overhead should be apparent.
If you'd prefer, you could consider the rate of fire of a gun in a multiplayer game.
Or a character's movement.
Or their health.
Or high-scores.
By keeping all of these things encapsulated in closures, they're untweakable.
That doesn't mean that the server is unhackable.
But it does mean that there's one less spot for people to get in, without rewriting your engine from the ground up.

It's kind of hard to tell what you're asking, but I see two possible questions and therefore two answers:
A JavaScript function is created once for each execution of the execution context in which you've defined it. So if that context is global (outside of any function), yes, each declaration or expression will create only one function. If that context is within a function, they'll be defined each time the function is called.
So for example, if this is a global scope:
function foo() { }
...only one of those will be created. In contrast, something like this:
function bar() {
return {
foo: function() { }
};
}
...creates a new function and assigns it to the foo property on the returned object each time bar is called. (That doesn't mean a smart JavaScript engine can't share the underlying code for them — and I'm told by people who claim to know that V8 [the engine in Chrome and elsewhere] does indeed reuse the code — but they'll be separate function objects.)
Each function declaration or expression creates its own function; if you have two equivalent declarations or expressions, they create two functions, even though they're equivalent. That doesn't mean that a smart JavaScript engine can't share the underlying code under-the-covers, but you'll still have two separate function objects.
So for example:
var a = function() { };
var b = function() { };
console.log(a === b); // "false"
// Adding a property to `a`, since functions are objects, demonstrates
// further that they are not the same function object
a.foo = "bar";
console.log(a.foo); // "bar"
console.log(b.foo); // "undefined"

No. The anonymous function
function(){
alert("some value");
}
is not the same as the anonymous function inside the object literal obj.
To make sure you 'recycle' a stored object or function, do somethign like this:
var f = function(){ alert('test') };
obj = {
m: f
}

Related

Is it possible to make a function self aware without external input

Background
I want a function keeping track of its own state:
var myObject = {
myFunction: function () {
var myself = this.myFunction;
var firstTime = Boolean(!myself.lastRetry);
if (firstTime) {
myself.lastRetry = Date.now();
return true;
}
// some more code
}
}
The problem with the above code is that the value of this will depend on the site of the function call. I want the function to be able to refer to itself without using:
myObject.myFunction
.bind()
.apply()
.call()
Question
Is it possible to give a function this kind of self awareness independent of its call site and without any help from external references to it?
If you want to store that state on the function instance, give the function a name, and use that name within it:
var myObject = {
myFunction: function theFunctionName() {
// ^^^^^^^^^^^^^^^--------------------- name
var firstTime = Boolean(!theFunctionName.lastRetry);
// ^--------------------------- using it
if (firstTime) {
theFunctionName.lastRetry = Date.now();
// ^------------------------------------------------ using it
return true;
}
// some more code
}
};
You'd do that whenever you want to use a function recursively as well. When you give a name to a function that way (putting the name after function and before (), that name is in-scope within the function's own code. (It's not in-scope for the code containing the function if it's a function expression, but it is if it's a function declaration. Yours is an expression.)
That's a named function expression (where previously you had an anonymous function expression). You may hear warnings about NFEs, but the issues various JavaScript implementations had with them are essentially in the past. (IE8 still handles them incorrectly, though: More in this post on my blog.)
You might consider keeping that state somewhere private, though, via an IIFE:
var myObject = (function(){
var lastRetry = null;
return {
myFunction: function() {
var firstTime = Boolean(!lastRetry);
if (firstTime) {
lastRetry = Date.now();
return true;
}
// some more code
}
};
})();
Now, nothing outside that outer anonymous function can see lastRetry at all. (And you don't have to worry about IE8, if you're supporting stubborn XP users. :-) )
Side note: The unary ! operator always returns a boolean, so your
var firstTime = Boolean(!theFunctionName.lastRetry);
...is exactly equivalent to:
var firstTime = !theFunctionName.lastRetry;
...but with an extra unnecessary function call. (Not that it hurts anything.)
Of course you can, simply give your function an internal named representation and it can refer to itself from there. For example...
var obj = {
doThings:function doThingsInternal(arg1, arg2) {
console.log(arg1, arg2);
for (var arg in doThingsInternal.arguments) {
console.log(arg);
}
}
};
obj.doThings('John', 'Doe');
You could use a simple Closure, if you are not too bent on keeping state existence knowledge within the function. But I guess you don't want that. Another way to do this could be changing the function itself on the first call. Benefits, no/less state variables needed and no costly checks on subsequent calls! -
var myObject = {
myFunction: function () {
// Whatever you wanna do on the first call...
// ...
// And then...
this.myFunction = function(){
// Change the definition to whatever it should do
// in the subsequent calls.
}
// return the first call value.
}
};
You can extend this model to any states by changing the function definition per your state.

Does this way of defining JS objects have any purpose?

I'm maintaining some legacy code and I've noticed that the following pattern for defining objects is used:
var MyObject = {};
(function (root) {
root.myFunction = function (foo) {
//do something
};
})(MyObject);
Is there any purpose to this? Is it equivalent to just doing the following?
var MyObject = {
myFunction : function (foo) {
//do something
};
};
I'm not about to embark in a holy quest to refactor the whole codebase to my likings, but I'd really like to understand the reason behind that roundabout way of defining objects.
Thanks!
It's called the module pattern http://toddmotto.com/mastering-the-module-pattern/
The main reason is for you to create truly private methods and variables. In your case, it's not meaningful because it's not hiding any implementation details.
Here's an example where it makes sense to use the module pattern.
var MyNameSpace = {};
(function(ns){
// The value variable is hidden from the outside world
var value = 0;
// So is this function
function adder(num) {
return num + 1;
}
ns.getNext = function () {
return value = adder(value);
}
})(MyNameSpace);
var id = MyNameSpace.getNext(); // 1
var otherId = MyNameSpace.getNext(); // 2
var otherId = MyNameSpace.getNext(); // 3
Whereas if you just used a straight object, adder and value would become public
var MyNameSpace = {
value: 0,
adder: function(num) {
return num + 1;
},
getNext: function() {
return this.value = this.adder(this.value);
}
}
And you could break it by doing stuff like
MyNameSpace.getNext(); // 1
MyNameSpace.value = 0;
MyNameSpace.getNext(); // 1 again
delete MyNameSpace.adder;
MyNameSpace.getNext(); // error undefined is not a function
But with the module version
MyNameSpace.getNext(); // 1
// Is not affecting the internal value, it's creating a new property
MyNameSpace.value = 0;
MyNameSpace.getNext(); // 2, yessss
// Is not deleting anything
delete MyNameSpace.adder;
MyNameSpace.getNext(); // no problemo, outputs 3
The purpose is to limit accessibility of functions within the closure to help prevent other scripts from executing code on it. By wrapping it around a closure you are redefining the scope of execution for all code inside the closure and effectively creating a private scope. See this article for more info:
http://lupomontero.com/using-javascript-closures-to-create-private-scopes/
From the article:
One of the best known problems in JavaScript is its dependance on a
global scope, which basically means that any variables you declare
outside of a function live in the same name space: the ominous
window object. Because of the nature of web pages, many scripts from
different sources can (and will) run on the same page sharing a
common global scope and this can be a really really bad thing as it
can lead to name collisions (variables with the same names being
overwritten) and security issues. To minimise the problem we can use
JavaScript’s powerful closures to create private scopes where we can
be sure our variables are invisible to other scripts on the page.
Code:
var MyObject = {};
(function (root) {
function myPrivateFunction() {
return "I can only be called from within the closure";
}
root.myFunction = function (foo) {
//do something
};
myPrivateFunction(); // returns "I can only be called from within the closure"
})(MyObject);
myPrivateFunction(); // throws error - undefined is not a function
advantages:
maintains variables in private scope.
you can extend the functionality of the existing object.
performance is increased.
i think the above three simple points are just enough to follow those rules. And to keep it simple its nothing but writing inner functions.
In the particular case that you show, there is no meaningful difference, in terms of functionality or visibility.
It's likely that the original coder adopted this approach as a sort of template allowing him to define private variables that could be used in the definition of things like myFunction:
var MyObject = {};
(function(root) {
var seconds_per_day = 24 * 60 * 60; // <-- private variable
root.myFunction = function(foo) {
return seconds_per_day;
};
})(MyObject);
This avoids calculating seconds_per_day each time the function is called, while also keeping it from polluting the global scope.
However, there's nothing essentially different from that and just saying
var MyObject = function() {
var seconds_per_day = 24 * 60 * 60;
return {
myFunction: function(foo) {
return seconds_per_day;
}
};
}();
The original coder may have preferred to be able to add functions to the object using the declarative syntax of root.myFunction = function, rather than the object/property syntax of myFunction: function. But that difference is mainly a matter of preference.
However, the structure taken by the original coder has the advantage that properties/methods can be easily added elsewhere in the code:
var MyObject = {};
(function(root) {
var seconds_per_day = 24 * 60 * 60;
root.myFunction = function(foo) {
return seconds_per_day;
};
})(MyObject);
(function(root) {
var another_private_variable = Math.pi;
root.myFunction2 = function(bar) { };
})(MyObject);
Bottom line, there is no need to adopt this approach if you don't need to, but there is also no need to change it, since it works perfectly well and actually has some advantages.
First pattern can be used as a module which takes an object and returns that object with some modifications. In other words, you can define such modules as follows.
var module = function (root) {
root.myFunction = function (foo) {
//do something
};
}
And use it like:
var obj = {};
module(obj);
So an advantage could be the re-usability of this module for later uses.
In the first pattern, you can define a private scope to store your private stuff such as private properties and methods. For example, consider this snippet:
(function (root) {
// A private property
var factor = 3;
root.multiply = function (foo) {
return foo * factor;
};
})(MyObject);
This pattern can be used to add a method or property to all types of objects such as arrays, object literals, functions.
function sum(a, b) {
return a + b;
}
(function (root) {
// A private property
var factor = 3;
root.multiply = function (foo) {
return foo * factor;
};
})(sum);
console.log(sum(1, 2)); // 3
console.log(sum.multiply(4)); // 12
In my opinion the main advantage could be the second one (creating a private scope)
This pattern provides a scope in which you can define helper functions that are not visible in the global scope:
(function (root) {
function doFoo() { ... };
root.myFunction = function (foo) {
//do something
doFoo();
//do something else
};
})(MyObject);
doFoo is local to the anonymous function, it can't be referenced from outside.

What is the exact use of closures in Javascript?

Hi still i'm not sure about the exact usage of using closures in javascript.I have idea about closures "A closure is an inner function that has access to the outer (enclosing) function’s variables—scope chain".But i don't know why we are using closures in javascript.
It allows you to succinctly express logic without needing to repeat yourself or supply a large number of parameters and arguments for a callback function.
There is more information available here: javascript closure advantages?
Imagine if instead of
alert("Two plus one equals" + (2+1) );
you'd be forced to declare a variable for every constant you ever use.
var Two = 2;
var One = 1;
var myString = "Two plus one equals";
alert(myAlert + (Two + One) );
You'd go crazy if you had to define a variable for every single constant before you can ever use it.
The access to local variables in case of closures is an advantage, but the primary role - usefulness - is the use of a function as a primary expression, a constant.
Take
function Div1OnClick()
{
Counter.clickCount ++;
}
$('#Div1').click(Div1OnClick);
versus
$('#Div1').click(function(){ Counter.clickCount++; });
You don't create a new function name in the "above" namespace just to use it once. The actual activity is right there where it's used - you don't need to chase it across the code to where it was written. You can use the actual function as a constant instead of first defining and naming it and then calling it by name, and while there are countless caveats, advantages and tricks connected to closures, that's the one property that sells them.
In general, the main use of closures is to create a function that captures the state from it's context. Consider that the function has the captured variables but they are not passed as parameters.
So, you can think of it of a way to create families of functions. For example if you need a series of function that only differ in one value, but you cannot pass that value as a parameter, you can create them with closures.
The Mozilla Developer Network has a good introduction to closures. It shows the following example:
function init() {
var name = "Mozilla";
function displayName() {
alert(name);
}
displayName();
}
init();
In this case the function displayName has captured the variable name. As it stand this example is not very useful, but you can consider the case where you return the function:
function makeFunc() {
var name = "Mozilla";
function displayName() {
alert(name);
}
return displayName;
}
var myFunc = makeFunc();
myFunc();
Here the function makeFunc return the function displayName that has captured the variable name. Now that function can be called outside by assigning it to the variable myFunc.
To continue with this example consider now if the captured variable name were actually a parameter:
function makeFunc(name) {
function displayName() {
alert(name);
}
return displayName;
}
var myFunc = makeFunc("Mozilla");
myFunc();
Here you can see that makeFunc create a function that shows a message with the text passed as parameter. So it can create a whole family of function that vary only on the value of that variable ("Mozilla" in the example). Using this function we can show the message multiple times.
What is relevant here is that the value that will be shown in the massage has been encapsulated. We are protecting this value in a similar fashion a private field of a class hides a value in other languages.
This allows you to, for example, create a function that counts up:
function makeFunc(value) {
function displayName() {
alert(value);
value++;
}
return displayName;
}
var myFunc = makeFunc(0);
myFunc();
In this case, each time you call the function that is stored in myFunc you will get the next number, first 0, next 1, 2... and so on.
A more advanced example is the "Counter" "class" also from the Mozilla Developer Network. It demonstrates the module pattern:
var Counter = (function() {
var privateCounter = 0;
function changeBy(val) {
privateCounter += val;
}
return {
increment: function() {
changeBy(1);
},
decrement: function() {
changeBy(-1);
},
value: function() {
return privateCounter;
}
}
})();
alert(Counter.value()); /* Alerts 0 */
Counter.increment();
Counter.increment();
alert(Counter.value()); /* Alerts 2 */
Counter.decrement();
alert(Counter.value()); /* Alerts 1 */
Here you can see that Counter is an object that has a method increment that advances the privateCounter variable, and the method decrement that decrements it. It is possible to query the value of this variable by calling the method value.
The way this is archived is with an auto-invocation of an anonymous function that creates a hidden scope where the varialbe privateCounter is declared. Now this variable will only be accessible from the functions that capture its value.
Closures are a powerful construct used to implement a lot of additional features in JavaScript. For instance a closure can be used to expose private state as follows:
function getCounter() {
var count = 0;
return function () {
return ++count;
};
}
var counter = getCounter();
alert(counter()); // 1
alert(counter()); // 2
alert(counter()); // 3
In the above example when we call getCounter we create a private variable count. Then we return a function which return count incremented. Hence the function we return is a closure in the sense that it closes over the variable count and allows you to access it even after count goes out of scope.
That's a lot of information stuffed in a few lines. Let's break it down?
Okay, so variables have a lifetime just like people do. They are born, they live and they die. The beginning scope marks the birth of a variable and the end of a scope marks the death of a variable.
JavaScript only has function scopes. Hence when you declare a variable inside a function it's hoisted to the beginning of the function (where it's born).
When you try to access a variable which is not declared you get a ReferenceError. However when you try to access a variable which is declared later on you get undefined. This is because declarations in JavaScript are hoisted.
function undeclared_variable() {
alert(x);
}
undeclared_variable();
When you try to access an undeclared variable you get a ReferenceError.
function undefined_variable() {
alert(x);
var x = "Hello World!";
}
undefined_variable();
When you try to access a variable which is declared later in the function you get undefined because only the declaration is hoisted. The definition comes later.
Coming back to scopes a variable dies when it goes out of scope (usually when the function within which the variable is declared ends).
For example the following program will give a ReferenceError because x is not declared in the global scope.
function helloworld() {
var x = "Hello World!";
}
helloworld();
alert(x);
Closures are interesting because they allow you to access a variable even when the function within which variable is declared ends. For example:
function getCounter() {
var count = 0;
return function () {
return ++count;
};
}
var counter = getCounter();
alert(counter()); // 1
alert(counter()); // 2
alert(counter()); // 3
In the above program the variable count is defined in the function getCounter. Hence when a call to getCounter ends the variable count should die as well.
However it doesn't. This is because getCounter returns a function which accesses count. Hence as long as that function (counter) is alive the variable count will stay alive too.
In this case the function which is returned (counter) is called a closure because it closes over the variable count which is called the upvalue of counter.
Uses
Enough with the explanation. Why do we need closures anyway?
As I already mentioned before the main use of closures is to expose private state as is the case with the getCounter function.
Another common use case of closures is partial application. For instance:
function applyRight(func) {
var args = Array.prototype.slice.call(arguments, 1);
return function () {
var rest = Array.prototype.slice.call(arguments);
return func.apply(this, rest.concat(args));
};
}
function subtract(a, b) {
return a - b;
}
var decrement = applyRight(subtract, 1);
alert(decrement(1)); // 0
In the above program we had a function called subtract. We used partial application to create another function called decrement from this subtract function.
As you can see the decrement function is actually a closure which closes over the variables func and args.
That's pretty much all you need to know about closures.
It is because of information hiding.
var myModule = (function (){
var privateClass = function (){};
privateClass.prototype = {
help: function (){}
};
var publicClass = function (){
this._helper = new privateClass();
};
publicClass.prototype = {
doSomething: function (){
this._helper.help();
}
};
return {
publicClass: publicClass
};
})();
var instance = new myModule.publicClass();
instance.doSomething();
In javascript you don't have classes with ppp (public, protected, private) properties so you have to use closures to hide the information. On class level that would be very expensive, so the only thing you can do for better code quality to use closure on module level, and use private helper classes in that closure. So closure is for information hiding. It is not cheap, it cost resources (memory, cpu, etc..) so you have to use closures just in the proper places. So never use it on class level for information hiding, because it is too expensive for that.
Another usage to bind methods to instances by using callbacks.
Function.prototype.bind = function (context){
var callback = this;
return function (){
return callback.apply(context, arguments);
};
};
Typical usage of bound function is by asynchronous calls: defer, ajax, event listeners, etc...
var myClass = function (){
this.x = 10;
};
myClass.prototype.displayX = function (){
alert(this.x);
};
var instance = new myClass();
setTimeout(instance.displayX.bind(instance), 1000); //alerts "x" after 1 sec

Javascript: Change value of variable inside conditional inside function

I'm trying to reuse a complicated function, and it would work perfectly if I could change the value of a local variable that's inside a conditional inside that function.
To boil it down:
var func = complicated_function() {
// lots of code
if (something) {
var localvar = 35;
}
// lots of code
}
I need localvar to be some other number.
Is there any way to assign localvar to something else, without actually modify anything in the function itself?
Update: The answer is yes! See my response below.
Is there any way to assign localvar to something else, without actually modify anything in the function itself?
Nope.
No, but it is possible to assign it conditionally so that the function signature (basically, the required input and output) does not change. Add a parameter and have it default to its current value:
var func = complicated_function(myLocalVar) {
// lots of code
if (something) {
// if myLocalVar has not been set, use 35.
// if it has been set, use that value
var localvar = (myLocalVar === undefined)?35:myLocalVar;
}
// lots of code
}
No.
Without changing the complicated function there is no way, in javascript you can manipilate this by using call and apply. You can override functions in the complicated function or add new if this is an option (but they won't be able to access the local variable localvar).
this is more for fun my real answer is still no.
If you are feeling crazy :)
var complicatedFunction = function() {
var i = 10;
var internalStuff = function() {
console.log(i); // 10 or 12?
};
return internalStuff();
};
var complicatedFunction;
eval("complicatedFunction = " + complicatedFunction.toString().replace(/i = 10/, 'i = 12'));
complicatedFunction(); //# => 12
If the function uses this.localvar:
var func = function() {
alert(this.localvar)
if (true) {
var localvar = 35;
}
// lots of code
alert(this.localvar)
}
var obj = {localvar: 10};
func.call(obj); // alerts 10 twice
If not, then you can't change it without changing the function.
In javascript variables are "pushed" to the top of their function. Variables in javascript have function scope, not "curly brace" scope like C, C++, Java, and C#.
This is the same code with you (the developer) manually pushing it to the top:
var func = complicated_function() {
var localvar = 0;
// lots of code
if (something) {
localvar = 35;
}
// lots of code
}
Does declaring the variable "up" one function help you out? At least the declaration is isolated.
function whatever() {
var localvar = 0;
var func = function() {
var something = true;
// lots of code
if (something) {
localvar = 35;
}
// lots of code
};
func();
alert(localvar);
}
whatever();
Here is the jsFiddle: http://jsfiddle.net/Gjjqx/
See Crockford:
http://javascript.crockford.com/code.html
JavaScript does not have block scope, so defining variables in blocks can confuse programmers who are experienced with other C family languages. Define all variables at the top of the function.
I asked this question about three weeks ago and within a half hour got five answers that all basically told me it wasn't possible.
But I'm pleased to announce that the answer is YES, it can be done!
Here's how:
var newfunc = func.toString().replace('35', '42');
eval('newfunc = ' + newfunc);
newfunc();
Of course, it uses eval, which probably means that it's evil, or at least very inadvisable, but in this particular case, it works.

Should I use a global variable and if not, what instead? (Javascript)

I'm working with several functions which need to pass a variable back and forth. Should I use a global variable or another method instead? I would also appreciate an example or two on how to implement it.
Thanks, Elliot Bonneville
Psuedocode of my functions:
function GetXML() {//this would be a function which reads in an XML file.
//Preferably it would also generate or set an object to hold the XML data.
}
function UseXMLData() { //I would use the XML data here.
}
function UseXMLDataHereAsWell() { //And here as well.
}
Global variables are, as you probably guessed, considered bad. Any other code on the page can modify them - often because another programmer accidentally picks the same name. You can try to mitigate this effect by choosing really strange names, but then you get a bunch of really strange names.
There are a lot of ways to minimize the number of global variables you create in JavaScript. One way is to store all your variables under a single object - that's what jQuery does (Technically jQuery uses two - $ and jQuery.)
If you know what you're doing, you often don't have to create any global variables - just wrap all your code in a function that you invoke immediately.
Bad example - pollutes the global namespace unnecessarily:
var appleCount = 0;
function addApple() {
appleCount = appleCount + 1;
}
function howManyApples() {
return appleCount;
}
addApple();
alert(howManyApples());
Better example - only creates one global variable:
var appleCounter = {
count: 0,
add: function() {
this.count = this.count + 1;
},
howMany: function() {
return this.count;
}
};
appleCounter.add();
alert(appleCounter.howMany());
Best example - creates no global variables:
(function(){
var appleCounter = {
count: 0,
add: function() {
this.count = this.count + 1;
},
howMany: function() {
return this.count;
}
};
appleCounter.add();
alert(appleCounter.howMany());
})();
The best solution for what you're trying to do would be to wrap all your data into an object and make your functions be methods on the object:
function MyXMLClass() {
this.data = null;
}
MyXMLClass.prototype = {
GetXML: function() {
this.data = ...;
},
UseXMLData: function() {
// use this.data
},
/* etc. */
};
And then you can just use it like this:
var x = new MyXMLClass();
x.GetXML();
x.UseXMLData();
...
Global variables should be avoided in reusable scripts.
If you're writing simple functions that will only be used in one page, there's nothing wrong with using globals.
If you're writing a reusable component or a complex web page, you should use closures or namespaces instead.
For more specific advice, please provide more detail.
EDIT:
You should create an XmlData class.
For example:
function XmlData(...) {
this.data = ...;
}
XmlData.prototype.doSomething = function(...) {
//Use this.data
}
Depending on how what your data comes from, you may want to make a separate function to retrieve the data.
Here is a good explanation.
Create a namespace, put all your functions within that namespace.
MyNS = {
x: 1, y: 2 // Here you define shared variables
};
MyNS.func1 = function(){}; // Here you define your functions that need those variables
Avoid global variables, it's bad programming. Try pass it as an argument or use name spacing to restrict its scope.

Categories

Resources