I've really looked all over for this and haven't found an answer that really explained this well...
I know how to access a global variable from within a function.
myGlobalVariable = [];
function myFunction() {
myGlobalVariable.push("somedata");
}
Now how do I access a variable one step up on the scope chain if it isn't global?
myGlobalVariable = [];
function myFunction() {
var notGlobalVariable = "somedata";
var myOtherFunction = function() {
myGlobalVariable.push(notGlobalVariable); // This is what I'd like to be able to do.
}
}
I know I could do something like
var notGlobalVariable = "somedata";
var myOtherFunction = function(arg) {
myGlobalVariable.push(arg);
}
myOtherFunction(notGlobalVariable);
But calling the function that way only works if I have the value of notGlobalVariable readily available. I'd like do be able to globally call the function and have it always use the value originally held by notGlobalVariable without having to pass that value in.
Edit
Alright, I kinda jumped the gun on this one. I though I was having a big variable scope issue, but apparently my issue was that in my specific code I was using the variable name arguments in place of notGlobalVariable, and as I should have known, arguments is shadowed and refers to the arguments passed in. I changed the name to args and it works fine. Sorry!
JavaScript does that automatically by creating closures.
Every function creates its own scope.
Scopes are nested, since functions can be defined within functions.
Every new nested scope ("function") can see all the variables that were defined in any parent scope at the point of its (i.e that new function's) creation. This is called a closure.
Every variable from any parent scope is "by reference" - child scopes ("functions") always see their current values.
The point in time when the function runs does not matter, only the point in time when it was declared (see first example).
The scope where a function runs in does not matter, only the scope a function was defined in (see second example).
Here
var myGlobalVariable = [];
// define function => creates closure #1
function myFunction() {
var notGlobalVariable = "somedata";
// define function => creates closure #2
var myOtherFunction = function() {
myGlobalVariable.push(notGlobalVariable);
}
// execute function
myOtherFunction();
}
myFunction(); // myGlobalVariable will be ["somedata"]
you create two scopes:
myFunction can see myGlobalVariable
the anonymous function stored in myOtherFunction can see myGlobalVariable and notGlobalVariable.
Now assume a small change:
var myGlobalVariable = [];
// define function => creates closure #1
function myFunction(callback) {
var notGlobalVariable = "somedata";
// define function => creates closure #2
var myOtherFunction = function() {
myGlobalVariable.push(callback());
}
// execute function
myOtherFunction();
}
// define function => creates closure #3
function foo() {
var thisIsPrivate = "really";
// define function => creates closure #4
return function () {
return thisIsPrivate;
}
}
myFunction(foo()); // myGlobalVariable will be ["really"]
You see that the callback function has access to thisIsPrivate because it was defined in the right scope, even though the scope it is executed in cannot see the variable.
Likewise the callback function will not be able to see notGlobalVariable, even though that variable is visible in the scope where the callback is executed.
Note that you always must use var on any variable you define. Otherwise variables will be silently global which can and will lead to hard to fix bugs in your program.
You do have access to notGlobalVariable inside of myOtherFunction. However you're only assigning myOtherFunction and never invoking it. Note that you'll have to invoke myOtherFunction inside of myFunction.
function myFunction() {
var notGlobalVariable = "somedata";
var myOtherFunction = function() {
myGlobalVariable.push(notGlobalVariable); // This is what I'd like to be able to do.
}
//Invoke myOtherFunction()
myOtherFunction()
}
Yes, you can - in javascript everything is possible - here is the fiddle http://jsfiddle.net/AZ2Rv/
myGlobalVariable = [];
function myFunction() {
var notGlobalVariable = "somedata";
// The following assigns a function to a variable
var myOtherFunction = function() {
myGlobalVariable.push(notGlobalVariable);
}
// The following line was missing in the code in the question so the function
// was never called and `notGlobalVariable` wasn't pushed into `myGlobalVariable`
myOtherFunction();
}
// And just to test if it works as expected
myFunction();
alert(myGlobalVariable[0]);
The problem of the OP laid actually in the code he didn't posted, but this sample code answers the original question - closures still work in javascript as expected.
Related
In my naive concept, a closure is simply a function return by another function, which preserve the scope of the outer function after it returns:
var factory = function(y){
var x = 2;
return function(){
console.log(x+y);
}
}
var closure1 = factory(2);
closure1(); // output 4
var closure2 = factory(10);
closure1(); // output 4
closure2(); // output 12
Though I do not understand why adding event handler in loop will create closures? (As shown in MDN) The event handler does not explicitly be returned, this is not the concern in this problem.
Then I came across another page, and at around Code snippet #2:, it said
The onclick function would create a closure if it referenced variables in its scope, but it doesn’t.
Does that mean that in the loop
nodes[i].onclick = function () { return false; }; is not closures
But if I changed it into
nodes[i].onclick = function () { console.log(i); return false; };
Then it becomes closure?
Combined the parts above, my concept to create a closure are
It needs to be a function returned in another function, or the callback function which attached in another function
The inner function MUST somehow access outer function's scope
Is it true that a closure is created iff 1 & 2 are satisfied?
a closure is simply a function return by another function, which preserve the scope of the outer function after it returns
Close.
It is a function which still has references pointing to it after the function that it was created inside has finished.
Returning it is one way to preserve a reference to it.
Though I do not understand why adding event handler in loop will create closures?
The reference is passed to the event handling code. This preserves it after the function which passed it there has finished.
Does that mean that in the loop …
Yes, it does.
It needs to be a function returned in another function, or the callback function which attached in another function
No. The reference can go anywhere, so long as it is preserved.
var obj = {};
function create() {
var foo = 1;
obj.bar = function() {
console.log(foo++);
};
}
create();
obj.bar();
obj.bar();
obj.bar();
obj.bar();
The inner function MUST somehow access outer function's scope
Yes
I have noticed something while playing around which has sparked a quick question.
When code is executed in the global/window context, any function declarations get added as methods to the window object.
But when I am in the context of another object, writing a function declaration does not add the method to my objects methods.
function functionInGlobalCtx() { // This will be added as a function to the window object
// code...
}
var myObject = {};
myObject.myObjectFunction = function () {
var $this = this; // The context here is the 'myObject' object
function functionHopefullyInMyObjectCtx() {
// code...
}
}
myObject.myObjectFunction();
Why does the function declaration exist as part of the window object but not the one for the object?
Is this simply 'how JavaScript works' (special rules apply to the global context?) or am I missing something?
Thanks.
Its actually understandable. Function is object. Myobject and myobjectfunction are two different objects. So are 'this' and function itself.
In your example, you define the hopefullyfunction in myobjfunction, not in myobject.
All functions declared globally will be attached to the global window object. That's how JavaScript works.
JavaScript only has function scope. So any function declared inside another function is private to the outer function.
The function functionHopefullyInMyObjectCtx can not be accessed from outside yet.
myObject.myObjectFunction = function () {
var $this = this;
function functionHopefullyInMyObjectCtx() {
// code...
}
}
Declaring a function inside a function does not attach it to the this automatically. However the function remains private and is only accessible within the scope it was declared in.
If you wanted to access the functionHopefullyInMyObjectCtx function from myObject.myObjectFunction then here is a way:
var myObject = {};
myObject.myObjectFunction = function () {
return {
functionHopefullyInMyObjectCtx: function() {
console.log('I got called');
}
}
}
obj = myObject.myObjectFunction();
//obj now has ref to the inner function
obj.functionHopefullyInMyObjectCtx();
I got called
Here is a good read: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions
I believe I have found the answer I was looking for.
Why are variables automatically assigned to the global/window object?
Because the JavaScript engine keeps a 'global environment record' of the items declared within the global scope (just like all scopes have an environment record holding all declaration information), but the difference between the global environment record and normal scope environment records is that the engine makes this record accessible within code (not just for engine internal use), through the window object!
If I am wrong or it's not quite right, please go ahead and correct me.
Thank you for your help.
https://es5.github.io/x10.html#x10.2.3
Difference between variable declaration syntaxes in Javascript (including global variables)?
Can someone explain why in the following function, I am able to pass an argument to a nested function? My understanding is that it has to do something with closures and scope(which I thought I had a decent understanding of), but I can seem to follow how exactly this argument is being passed.
The below function outputs 1,2 respectively. But how is the return statement doThis() getting the argument/parameter for "a"? I cant figure where/how this is accessed/passed.
function doSomething(){
var b = 1;
return function doThis(a){
console.log(b);//1
console.log(a);//2
}
}
var exec = doSomething();
exec(2);
The function doSomething() returns another function so when you execute
var exec = doSomething();
You can think of that exec as containing the following function
function doThis(a){ // <- takes an argument
console.log(1); // comes from the b argument in the outer scope
console.log(a); // not set yet
}
Thus when you call exec(2) you are actually calling doThis() with an argument 2 which becomes the value of a.
This is a slightly simplified version. To expand on that, the doSomething() function is described as closing over doThis() creating a closure. Conversely, the function doThis() is closed over or inside a closure. The closure itself is simply a limited state around the function:
function doSomething(){ // --> defines the closure
var b = 1; // variable only visible within doSomething()
return function doThis(a){ //<--> function has access to everything in doSomething(). Also defines another closure
console.log(b); // --> accesses the OUTER scope
console.log(a); // <-- comes from the INNER scope
} // <-- end INNER scope
} // --> end OUTER scope
When you execute doSomething() the returned result still retains access to the scope within it, this is why doThis() has access to the value b - it's simply reachable for it. It's similar how you can do
var foo = 40;
function bar(value) {
return foo + value;
}
console.log(bar(2));
Only in this instance any other code will have acces to foo as it's a global variable, so if you do foo = 100 in a different function, that will change the output of bar(). A closure prevents the code inside from being reachable from outside the closure.
When you assign var exec = doSomething();, exec is basically writing:
var doSomething = function(a) {
console.log(b);
console.log(a);
}
It became its own function. So passing in 2 like so exec(2) works like any normal function except that it has the variable b available to it because of the closure.
The following program returns "local" and, according to the tutorial Im reading, it is designed to demonstrate the phenomenon ofclosure`
What I don`t understand is why, at the end, in order to call parentfunction, it assigns it to the variable "child" and then calls "child."
Why doesn`t it work by just writing parentFunction(); at the end?
var variable = "top-level";
function parentFunction() {
var variable = "local";
function childFunction() {
print(variable);
}
return childFunction;
}
var child = parentFunction();
child();
parentFunction() returns another function which you assign to var child. Then, you call child() to invoke the function returned by the call to parentFunction().
Running just parentFunction(); at the end wouldn't do anything useful because you would just discard its return value which is a function. But this would work:
parentFunction()();
See this fiddle: http://jsfiddle.net/USCjn/
Update: A simpler example:
function outer() { // outer function returns a function
return function() {
alert('inner function called');
}
}
x = outer(); // what is now in x? the inner function
// this is the same as saying:
// x = function() {
// alert('inner function called');
// }
x(); // now the inner function is called
See this fiddle: http://jsfiddle.net/bBqPY/
Functions in JavaScript can return functions (that can return functions (that can return functions ...)). If you have a function that returns another function then it means that when you call the outer function what you get is the inner function but it is not called yet. You have to call the value that you got as a function to actually run the body of the inner function. So:
x = f();
means - run a function f and store what it returns (which may be a string, a number, an object, an array, or a function) in x. But this:
x = f()();
means - run a function f, expect it to return a function and run that returned function as well (the second parentheses) and store in x what the returned function returned.
The function f here is a higher order function because it returns another function. Functions can also take another functions as arguments. One of the most powerful ideas of functional programming languages in general and JavaScript in particular is that functions are just normal values like arrays or numbers that can be returned and passed around.
You have to first grasp the idea of higher order functions to understand closures and the event system in JavaScript.
2016 Update
Note that currently this:
function outer() {
return function() {
alert('inner function called');
}
}
can be written as:
let outer = () => () => alert('inner function called');
using the ES6 arrow function syntax.
The amazing part about closures is that an inner function (in this case, childFunction) can refer to variables outside of its scope (in this case, variable). parentFunction doesn't return the result of childFunction, but an actual reference to the function!
This means that when you do the following...
var child = parentFunction();
...now, child has a reference to childFunction, and childFunction still has access to any variables it had when the function was created, even if they no longer exist.
In order to have parentFunction call childFunction, you'd need to change your code as follows:
From...
return childFunction;
To:
return childFunction();
Douglas Crockford (Pioneer of JSON, among other things) has a whole article devoted to closures, and scoping in javascript, and it would be well worth it to check out his other articles on javascript.
The point that is being demonstrated is that the function that was returned and assigned to child is still referencing the variable that was declared inside parentFunction instead of the one that was declared outside where child() is being invoked.
The only way to create a variable scope in javascript is in a function body. Normally the variable inside the parentFunction would have been discarded after the function returned.
But because you declared a function inside parentFunction that referenced variable in that scope and passed it out of parentFunction, the variable in the parentFunction is retained via the reference made in the new function.
This protects variable from outside manipulation except by functions that closed around it inside parentFunction.
If a variable could be defined in a function, even if no value is assigned, it becomes a local variable
so, is testB() better programming?
var test = 'SNAP!'
function testA(boolean) {
if (boolean) var test = 'OK';
else var test = null;
alert(test);
}
function testB(boolean) {
if (boolean) var test = 'OK';
alert(test);
}
testA(true); // 'OK'
testB(true); // 'OK'
testA(false); // null
testB(false); // undefined, no error
In my specific case test's global value ('SNAP!') is neither expected nor required.
You can't declare variables conditionally.
Why?
The variable instantiation process occurs before the actual code execution, at the time the function is executed, those variables will be already bound to the local scope, for example:
function foo () {
if (false) {
var test = 'foo'; // never executed
}
return test;
}
foo(); // undefined
When the function is about to be executed, identifiers of formal parameters, identifiers from variable declarations, and identifiers from function declarations within the function's body are bound to the local variable environment.
Variables are initialized with undefined.
Also, identifiers in the local scope shadow the others with the same name, higher in the scope chain, for example:
var test = 'global';
function bar () {
alert(test); // undefined, not "global", the local variable already declared
var test = 'xxx';
}
bar();
If the test variable were not declared anywhere, a ReferenceError will be thrown:
function foo () {
return test;
}
try {
foo(); // ReferenceError!!
} catch (e) {
alert(e);
}
That's one of the reasons about why for example, JSLint recommends only one var statement at the top of functions, because for example, the first snippet, will actually resemble this when executed:
function foo () {
var test; // var statement was "hoisted"
if (false) {
test = 'foo'; // never executed
}
return test;
}
foo(); // undefined
Another reason is because blocks don't introduce a new lexical scope, only functions do it, so having a var statement within a look might make you think that the life of the variable is constrained to that block only, but that's not the case.
Nested function declarations will have a similar behavior of hoisting, they will be declared before the code execution, but they are initialized in that moment also:
function foo () {
return typeof bar;
// unreachable code:
function bar() {
//..
}
}
foo(); // "function"
If the variable does not need to be manipulated by any other functions, keep the variable inside a function with var foo;.
Otherwise, if it does need to be accessed and read in multiple scopes, keep it outside. But remember that when you keep it outside, it becomes global. That is, unless you wrap everything in a self executing function, which is the best way:
(function() {
var president='bush';
function blah() {
president='reagan';
}
function meh() {
president= 'carter';
}
document.getElementById('reagan').onclick=blah;
document.getElementById('carter').onclick=meh;
})();
alert( president ) // undefined
The above is perfect for a variable accessed by functions defined inside of that scope. Since there are 2 elements i click to set the president, it makes sense to define it outside both functions because they set the same variable.
So, If you are not dealing with multiple functions changing the exact same variable, keep them local to the function.
Is testB better programming? No, because it gives an unexpected result of "undefined" (at least, I was surprised by that) and it is hard to read.
Generally, variables should be limited to the scope that requires them, so if the "test" variable is not needed outside the function it should be declared local. To avoid confusion, declare your variable before using it:
function testC(boolean) {
var test;
if (boolean) {
test = "OK";
}
else {
test = null;
}
alert(test);
}
Unless you genuinely want to change the global scope version of "test", in which case don't use the var keyword inside the function.
If you ever find yourself using the same name for a local variable and a global variable you might consider renaming one of them.