Keep track of variables in Higher order functions - javascript

Can anybody please explain how variable value can exist after finish running the function?
I saw a code example of Higher order function but I don't understand how it keep track of variable in function after each run of the function.
in example below how variable count can add more after each run?
// Higher order functions
// A higher order function is any function that does at least one of the following
// 1. Accepts a function as an argument
// 2. Returns a new function
// Receives a function as an argument
const withCount = fn => {
let count = 0
// Returns a new function
return (...args) => {
console.log(`Call counts: ${++count}`)
return fn(...args)
}
}
const add = (x, y) => x + y
const countedAdd = withCount(add)
console.log(countedAdd(1, 2))
console.log(countedAdd(2, 2))
console.log(countedAdd(3, 2))

Note that the withCount function is called only once:
const countedAdd = withCount(add)
After that call, the variable count is created, and because they still have possible references in the same scope as it exists, it is not destroyed, making possible the use inside the scope.
Please note that the arrow function returned is inside the scope(function withCount).

What if¹ there would be no variables at all? What if there would only be a tree of, lets say objects? Each object has a list of key-value pairs, and a reference to its parent. Now how could we emulate variables with that tree? Well for global variables that is easy, we have to have some reference to the "global scope object" somehow, then we can add a key-value pair to that:
// var test = "value";
global.test = "value";
Now how do we represent a local scope? Quite easy: whenever a function gets called, we create a new such object, and let the parent reference point to the root object.
local.parent -> global
local.count = 0;
Now from that local function scope we can both look up local variables (count for example) and global ones, simply by traversing to the parent of the current scope and checking the variable there (test for example).
And for a function inside a function? Thats easy too: We just let the parent of the current scope object point to the one of the outer function:
local2.parent -> local
Now to look up count in that inner scope, we can go to the parent and find it as a property there.
Now the trick is, that those "context objects" do not disappear when the function ends execution, but rather when all references to it were lost.
Now we need another trick to make your example work:
A function declaration has to keep a reference to its parent scope, so when the function gets called, we can let the local scopes parent point to the parent scope.
Therefore if you do return (...args) => {, a reference will be kept to the "current scope object" (which contains count) and will be stored on the function. When you call it, the function will be executed with a new scope object, and that can access count through the parent reference. As long as you keep a reference to that function, the internal reference to that "scope object" will be kept, and that contains count.
¹ actually, this is exactly what happens. The ECMA spec calls these "scope objects" EnvironmentRecord ...

The thing you see here is called closure. You can find many good articles, books, explaining this concept. Basically, it's keeping an implicit reference to a variable.
The returned function below closes over variable `count`
return (...args) => ...
So when you call withCount, you retain a secret reference to count. And the other functions you called, just keep interacting with that variable.

Related

Javascript hide the context

What's the best way for a method to call another method and pass the arguments in not-by-reference fashion?
i.e.
function main() {
let context = {};
// Pass context to someOtherFunction
// Such that console.log(context) in this function does not show `{whatever: true}`
}
function someOtherFunc(context) {
context.whatever = true;
}
I realize I can clone the context and pass that. But I was wondering if there was another way to do this, maybe using anonymous function wrap?
Okay, let's break this down a bit
const context = {x: true};
Above, you create an object (named context) in the global scope.
function(x) {
"use strict";
x.y = true;
}
You create an anonymous function that takes a reference to an object, and adds a new property y to that object
(/*...*/)(context);
You wrapped the above function into an IIFE so it immediately executes. For the parameter, you supplied a reference to the global context object, which is referenced by x inside the IIFE.
Objects are passed around by reference. Passing context in to the function doesn't create a new object x that is a copy of the context, it creates a new reference x that references the same object that context references.
If you need to actually copy the provided object into a new object, you need to do that yourself. As mentioned above, one mechanism is to stringify the object into JSON and then parse the JSON back to a new object. There are others depending on what you need to accomplish.
This isn't even a scope or context question at all - it's passing a reference to an object in to a function. Even if your IIFE had no way whatsoever of directly accessing the context variable, once you pass a reference to that object as an input to the function, the function has the reference and can do what it likes to it.
You also seem to misunderstand about how IIFEs hide data. You hide things inside the IIFE from things outside, not vice versa. Even then, it won't prevent you from passing a reference outside of the IIFE. Here's an example:
function changeName(animal) {
"use strict"
//myDog.name = "Rex"; // Error - myDog isn't a valid reference in this scope
//myCat.name = "Rex"; // Error - myCat isn't a valid reference in this scope either
animal.name = "Rex"; // Perfectly legal
}
(function () {
var myDog = {name: "Rover"};
var myCat = {name: "Kitty"};
console.log(myDog);
console.log(myCat);
changeName(myDog); // Even though changeName couldn't directly access myDog, if we give it a reference, it can do what it likes with it.
console.log(myDog);
})()
In this case, changeName has no access to myDog or myCat which are purely contained within the closure formed by the IIFE. However, the code that exists within that IIFE is able to pass a reference to myDog to changeName and allow it to change the name of the dog, even though changeName still couldn't access the object using the myDog variable.
This is because you are not technically redefining x, but adding properties to it.
I didn't really understood where your doubts came from so this is (to the best of my knowledge) an explanation of what your code is doing.
I'll try to translate the code to human-english.
Define the variable context in the "global scope". (It can be read from anywhere)
It cannot be redefined because its a constant.
Afterwards, define an anonymous self-invoking function (which "starts" a new "local scope" above the global scope so it has access to everything the global scope had access to)
This self invoking function grabs parameter x and adds the property y with a value of true to x and calls itself with the variable context
Read the value of context.
Please read:
JavaScript Scope
JavaScript Function Definitions (Self-Invoking Functions)

Javascript Function Declaration Options

I've seen experts using below to declare a function:
(function () {
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
//etc
}());
e.g.
https://github.com/douglascrockford/JSON-js/blob/master/json.js
Could someone help me understand when should we use above pattern and how do we make use of it?
Thanks.
Well, since ECMA6 hasn't arrived yet, functions are about the best way to create scopes in JS. If you wrap a variable declaration of sorts in an IIFE (Immediately Invoked Function Expression), that variable will not be created globally. Same goes for function declarations.
If you're given the seemingly daunting task of clearing a script of all global variables, all you need to do is wrap the entire script in a simple (function(){/*script here*/}());, and no globals are created, lest they are implied globals, but that's just a lazy fix. This pattern is sooo much more powerful.
I have explained the use of IIFE in more detail both here, here and here
The basic JS function call live-cycle sort of works like this:
f();//call function
||
====> inside function, some vars are created, along with the arguments object
These reside in an internal scope object
==> function returns, scope object (all vars and args) are GC'ed
Like all objects in JS, an object is flagged for GC (Garbage Collection) as soon as that object is not referenced anymore. But consider the following:
var foo = (function()
{
var localFoo = {bar:undefined};
return function(get, set)
{
if (set === undefined)
{
return localFoo[get];
}
return (localFoo[get] = set);
}
}());
When the IIFE returns, foo is assigned its return value, which is another function. Now localFoo was declared in the scope of the IIFE, and there is no way to get to that object directly. At first glance you might expect localFoo to be GC'ed.
But hold on, the function that is being returned (and assigned to foo still references that object, so it can't be gc'ed. In other words: the scope object outlives the function call, and a closure is created.
The localFoo object, then, will not be GC'ed until the variable foo either goes out of scope or is reassigned another value and all references to the returned function are lost.
Take a look at one of the linked answers (the one with the diagrams), In that answer there's a link to an article, from where I stole the images I used. That should clear things up for you, if this hasn't already.
An IIFE can return nothing, but expose its scope regardless:
var foo = {};
(function(obj)
{
//obj references foo here
var localFoo = {};
obj.property = 'I am set in a different scope';
obj.getLocal = function()
{
return localFoo;
};
}(foo));
This IIFE returns nothing (implied undefined), yet console.log(foo.getLocal()) will log the empty object literal. foo itself will also be assigned property. But wait, I can do you one better. Assume foo has been passed through the code above once over:
var bar = foo.getLocal();
bar.newProperty = 'I was added using the bar reference';
bar.getLocal = function()
{
return this;
};
console.log(foo.getLocal().newProperty === bar.newProperty);
console.log(bar ==== foo.getLocal());
console.log(bar.getLocal() === foo.getLocal().getLocal());
//and so on
What will this log? Indeed, it'll log true time and time again. Objects are never copied in JS, their references are copied, but the object is always the same. Change it once in some scope, and those changes will be shared across all references (logically).
This is just to show you that closures can be difficult to get your head round at first, but this also shows how powerful they can be: you can pass an object through various IIFE's, each time setting a new method that has access to its own, unique scope that other methdods can't get to.
Note
Closers aren't all that easy for the JS engines to Garbage Collect, but lately, that's not that big of an issue anymore.
Also take your time to google these terms:
the module pattern in JavaScript Some reasons WHY we use it
closures in JavaScript Second hit
JavaScript function scope First hit
JavaScript function context The dreaded this reference
IIFE's can be named functions, too, but then the only place where you can reference that function is inside that function's scope:
(function init (obj)
{
//obj references foo here
var localFoo = {};
obj.property = 'I am set in a different scope';
obj.getLocal = function()
{
return localFoo;
};
if (!this.wrap)
{//only assign wrap if wrap/init wasn't called from a wrapped object (IE foo)
obj.wrap = init;
}
}(foo));
var fooLocal = foo.getLocal();
//assign all but factory methods to fooLocal:
foo.wrap(fooLocal);
console.log(fooLocal.getLocal());//circular reference, though
console.log(init);//undefined, the function name is not global, because it's an expression
This is just a basic example of how you can usre closures to create wrapper objects...
Well the above pattern is called the immediate function. This function do 3 things:-
The result of this code is an expression that does all of the following in a single statement:
Creates a function instance
Executes the function
Discards the function (as there are no longer any references to it after the statement
has ended)
This is used by the JS developers for creating a variables and functions without polluting the global space as it creates it's own private scope for vars and functions.
In the above example the function f(){} is in the private scope of the immediate function, you can't invoke this function at global or window scope.
Browser-based JavaScript only has two scopes available: Global and Function. This means that any variables you create are in the global scope or confined to the scope of the function that you are currently in.
Sometimes, often during initialization, you need a bunch of variables that you only need once. Putting them in the global scope isn't appropriate bit you don't want a special function to do it.
Enter, the immediate function. This is a function that is defined and then immediately called. That's what you are seeing in Crockford's (and others') code. It can be anonymous or named, without defeating the purpose of avoiding polluting the global scope because the name of the function will be local to the function body.
It provides a scope for containing your variables without leaving a function lying around. Keeps things clean.

Understanding Javascript scope with "var that = this" [duplicate]

This question already has answers here:
In Javascript, why is the "this" operator inconsistent?
(8 answers)
Closed 9 years ago.
Say I have the following property method in an object:
onReady: function FlashUpload_onReady()
{
Alfresco.util.Ajax.jsonGet({
url: Alfresco.constants.PROXY_URI + "org/app/classification",
successCallback: {
fn: function (o) {
var classButtonMenu = [],
menuLabel, that = this;
var selectButtonClick = function (p_sType, p_aArgs, p_oItem) {
var sText = p_oItem.cfg.getProperty("text");
that.classificationSelectButton.set("label", sText);
};
for (var i in o.json.items) {
classButtonMenu.push({
text: o.json.items[i].classification,
value: o.json.items[i].filename,
onClick: {fn: selectButtonClick}
});
}
this.classificationSelectButton = new YAHOO.widget.Button({
id: this.id + "-appClassification",
type: "menu",
label: classButtonMenu[0].text,
name: "appClassification",
menu: classButtonMenu,
container: this.id + "-appClassificationSection-div"
});
},
scope: this
},
failureMessage: "Failed to retrieve classifications!"
});
It took me some guess work to figure out that in the selectButtonClick function that I needed to reference that instead of this in order to gain access to this.classificationSelectButton (otherwise it comes up undefined), but I'm uncertain as to why I can't use this. My best guess is that any properties in the overall object that gets referenced within new YAHOO.widget.Button somehow looses scope once the constructor function is called.
Could someone please explain why it is that I have to reference classificationSelectButton with var that = this instead of just calling `this.classificationSelectButton'?
The most important thing to understand is that a function object does not have a fixed this value -- the value of this changes depending on how the function is called. We say that a function is invoked with some a particular this value -- the this value is determined at invocation time, not definition time.
If the function is called as a "raw" function (e.g., just do someFunc()), this will be the global object (window in a browser) (or undefined if the function runs in strict mode).
If it is called as a method on an object, this will be the calling object.
If you call a function with call or apply, this is specified as the first argument to call or apply.
If it is called as an event listener (as it is here), this will be the element that is the target of the event.
If it is called as a constructor with new, this will be a newly-created object whose prototype is set to the prototype property of the constructor function.
If the function is the result of a bind operation, the function will always and forever have this set to the first argument of the bind call that produced it. (This is the single exception to the "functions don't have a fixed this" rule -- functions produced by bind actually do have an immutable this.)
Using var that = this; is a way to store the this value at function definition time (rather than function execution time, when this could be anything, depending on how the function was invoked). The solution here is to store the outer value of this in a variable (traditionally called that or self) which is included in the scope of the newly-defined function, because newly-defined functions have access to variables defined in their outer scope.
Because this changes its value based on the context it's run in.
Inside your selectButtonClick function the this will refer to that function's context, not the outer context. So you need to give this a different name in the outer context which it can be referred to by inside the selectButtonClick function.
There's lexical scope: variables declared in functions and arguments passed to functions are visible only inside the function (as well as in its inner functions).
var x = 1; // `1` is now known as `x`
var that = this; // the current meaning of `this` is captured in `that`
The rules of lexical scope are quite intuitive. You assign variables explicitly.
Then there's dynamic scope: this. It's a magical thing that changes it's meaning depending on how you call a function. It's also called context. There are several ways to assign a meaning to it.
Consider a function:
function print() { console.log(this); }
Firstly, the default context is undefined in strict mode and the global object in normal mode:
print(); // Window
Secondly, you can make it a method and call it with a reference to an object followed by a dot followed by a reference to the function:
var obj = {};
obj.printMethod = print;
obj.printMethod(); // Object
Note, that if you call the method without the dot, the context will fall back to the default one:
var printMethod = obj.printMethod;
printMethod(); // Window
Lastly, there is a way to assign a context is by using either call/apply or bind:
print.call(obj, 1, 2); // Object
print.apply(obj, [ 1, 2 ]); // Object
var boundPrint = print.bind(obj);
boundPrint(); // Object
To better understand context, you might want to experiment with such simple examples. John Resig has very nice interactive slides on context in JavaScript, where you can learn and test yourself.
Storing it in a variable lets you access it in other scopes where this may refer to something else.
See https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/this, http://www.quirksmode.org/js/this.html and What is the scope of variables in JavaScript? for more information about the this keyword.
The this reference doesn't work when a method of a class is called from a DOM event. When a method of an object is used as an event handler for onclick, for example, the this pointer points to the DOM node where the event happened. So you have to create a private backup of this in the object.
this is a keyword in javascript, not a default variable defined within every function, hence, as Gareth said, this will refer to the context in which the function is invoked, or the global object if there's no context.

Clarification of JavaScript variable scope

I already know how to make this code work, but my question is more about why does it work like this, as well as am I doing stuff right.
The simplest example I can make to showcase my issue is this :
Lets say I have a function that increments the value of an input field by 10 on the press of a button.
var scopeTest = {
parseValue : function( element, value ) {
value = parseInt( element.val(), 10 );
//Why does this not return the value?
return value;
},
incrementValue : function( element, button, value ) {
button.on('mousedown', function (e) {
//Execute the parseValue function and get the value
scopeTest.parseValue( element, value );
//Use the parsed value
element.val( value + 10 );
e.preventDefault();
});
},
init : function () {
var element = $('#test-input'),
button = $('#test-button'),
value = '';
this.incrementValue( element, button, value );
}
};
scopeTest.init();
The above code doesnt work because the parseValue method doesn't properly return the value var when executed inside the incrementValue method.
To solve it apparently I have to set the scopeTest.parseValue( element, value ); parameter to the value variable like this:
value = scopeTest.parseValue( element, value );
Than the code works.
But my question is why? Why is this extra variable assignment step necessary, why the return statement is not enough? Also I am doing everything right with my functions/methods, or is this just the way JavaScript works?
Working example here => http://jsfiddle.net/Husar/zfh9Q/11/
Because the value parameter to parseValue is just a reference. Yes, you can change the object, because you have a reference, but if you assign to the reference it now points at a different object.
The original version is unchanged. Yes, the return was "enough", but you saved the new object in a variable with a lifetime that ended at the next line of code.
People say that JavaScript passes objects by reference, but taking this too literally can be confusing. All object handles in JavaScript are references. This reference is not itself passed by reference, that is, you don't get a double-indirect pointer. So, you can change the object itself through a formal parameter but you cannot change the call site's reference itself.
This is mostly a scope issue. The pass-by-* issue is strange to discuss because the sender variable and the called functions variable have the same name. I'll try anyway.
A variable has a scope in which it is visible. You can see it as a place to store something in. This scope is defined by the location of your function. Meaning where it is in your source code (in the global scope or inside a function scope). It is defined when you write the source code not how you call functions afterwards.
Scopes can nest. In your example there are four scopes. The global scope and each function has a scope. The scopes of your functions all have the global scope as a parent scope. Parent scope means that whenever you try to access a name/variable it is searched first in the function scope and if it isn't found the search proceeds to the parent scope until the name/variable is found or the global scope has been reached (in that case you get an error that it can't be found).
It is allowed to define the same name multiple times. I think that is the source of your confusion. The name "value" for your eyes is always the same but it exists three times in your script. Each function has defined it: parseValue and incrementValue as parameter and init as local var. This effect is called shadowing. It means that all variables with name 'value' are always there but if you lookup the name one is found earlier thus making the other invisible/shadowed.
In this case "value" is treated similar in all three functions because the scope of a local var and a parameter is the same. It means that as soon as you enter one of the methods you enter the function scope. By entering the scope the name "value" is added to the scope chain and will be found first while executing the function. And the opposite is true. If the function scope is left the "value" is removed from the scope chain and gets invisible and discarded.
It is very confusing here because you call a function that takes a parameter "value" with something that has the name "value" and still they mean different things. Being different there is a need to pass the value from one "value" to the other. What happens is that the value of the outer "value" is copied to the inner "value". That what is meant with pass-by-value. The value being copied can be a reference to an object which is what most people make believe it is pass-by-reference. I'm sorry if that sounds confusing but there is too much value naming in here.
The value is copied from the outer function to the called function and lives therefor only inside the called function. If the function ends every change you did to it will be discarded. The only possibility is the return your "side effect". It means your work will be copied back to a variable shortly before the function gets discarded
To other alternative is indeed leaving of parameters and work with the scope chain, e.g. the global scope. But I strongly advize you not to do that. It seems to be easy to use but it produces a lot of subtle errors which will make your life much harder. The best thing to do is to make sure variables have the most narrow scope (where they are used) and pass the values per function parameters and return values.
This isn't a scoping issue, it's a confusion between pass-by-reference and pass-by-value.
In JavaScript, all numbers are passed by value, meaning this:
var value = 10;
scopeTest.parseValue( element, value );
// value still == 10
Objects, and arrays are passed by reference, meaning:
function foo( obj ){
obj.val = 20;
}
var value = { val: 10 }
foo( value );
// value.val == 20;
As others have said it's a pass-by-ref vs pass-by-val.
Given: function foo (){return 3+10;} foo();
What happens? The operation is performed, but you're not setting that value anywhere.
Whereas: result = foo();
The operation performs but you've stored that value for future use.
It is slightly a matter of scope
var param = 0;
function foo( param ) {
param = 1;
}
foo(param);
console.log(param); // still retains value of 0
Why?
There is a param that is global, but inside the function the name of the argument is called param, so the function isn't going to use the global. Instead param only applies the local instance (this.param). Which, is completely different if you did this:
var param = 0;
function foo() { // notice no variable
param = 1; // references global
}
foo(param);
console.log(param); // new value of 1
Here there is no local variable called param, so it uses the global.
You may have a look at it.
http://snook.ca/archives/javascript/javascript_pass

Difference between creating a global variable, vs one in a constructor function in JavaScript

If I declare a global variable x as:
var x = "I am window.x";
x will be a public property of the window object.
If I call a global function (without using "call", "apply" or attaching it to another object first), the window object will be passed in as the context (the “this” keyword).
It is like it is siting the x property on the current context, which happens to be the window.
If, however, I declare a variable in the same way inside a function, then use that function as a constructor, the property x will not be a public property of the object I just constructed (the current context). I am happy (I know I can do this.x = …), but it just seems like a bit of a contradiction.
Have I misunderstood something (about it being a contradiction / different behaviour)? Would anyone be able to explain what is going on, or is it just something I have to accept?
Hope that my question is clear.
It seems like you've understood it just fine (I pick one small nit with your terminology below). Local variables within constructor functions are just that: Local variables inside constructor functions. They're not part of the instance being initialized by the constructor function at all.
This is all a consequence of how "scope" works in JavaScript. When you call a function, an execution context (EC) is created for that call to the function. The EC has something called the variable context which has a binding object (let's just call it the "variable object," eh?). The variable object holds all of the vars and function arguments and other stuff defined within the function. This variable object is a very real thing and very important to how closures work, but you can't directly access it. Your x in the constructor function is a property of the variable object created for the call to the constructor function.
All scopes have a variable object; the magic is that the variable object for the global scope is the global object, which is window on browsers. (More accurately, window is a property on the variable object that refers back to the variable object, so you can reference it directly. The variable objects in function calls don't have any equivalent property.) So the x you define at global scope is a property of window.
That terminology nit-picking I promised: You've said:
If call a global function, the window object will be passed in as the context (the “this” keyword).
Which is mostly true. E.g., if you call a global function like this:
myGlobalFunction();
...then yes, this will be the global object (window) during the call. But there are lots of other ways you might call that global function where it won't be. For instance, if you assign that "global" function to a property on an object and then call the function via that property, this within the call will be the object the property belongs to:
var obj = {};
obj.foo = myGlobalFunction;
obj.foo(); // `this` is `obj` within the call, not `window`
obj['foo'](); // Exactly the same as above, just different notation
or you might use call or apply features of function objects to set this explicitly:
var obj = {};
myGlobalFunction.call(obj, 1, 2, 3); // Again, `this` will be `obj`
myGlobalFunction.apply(obj, [1, 2, 3]); // Same (`call` and `apply` just vary
// in terms of how you pass arguments
More to explore (disclosure: these are links to my blog, but it doesn't have ads or anything, seems unlikely I'll add them):
Closures are not complicated (explores the scope chain and variable objects and such)
Mythical methods (more about functions and this)
You must remember this (even more about functions and this)
Update: Below you've said:
I just want to check my understanding: In any scope (global or function) there are always 2 objects: a “this” object (what is that called?) and a “variable object”. In the global scope, these 2 objects are the same. In a function’s scope, they are different, and the “variable object” is not accessible. Is that correct?
You're on the right track, and yes, there are always those two things kicking around (usually more; see below). But "scope" and this have nothing to do with each other. This is surprising if you're coming to JavaScript from other languages, but it's true. this in JavaScript (which is sometimes called "context" although that can be misleading) is defined entirely by how a function is called, not where the function is defined. You set this when calling a function in any of several ways (see answer and links above). From a this perspective, there is no difference whatsoever between a function defined a global scope and one defined within another function. Zero. Zilch.
But yes, in JavaScript code (wherever it's defined) there's always this, which may be anything, and a variable object. In fact, there are frequently multiple variable objects, arranged in a chain. This is called the scope chain. When you try to retrieve the value of a free variable (an unqualified symbol, e.g. x rather than obj.x), the interpreter looks in the topmost variable object for a property with that name. If it doesn't find one, it goes to the next link in the chain (the next outer scope) and looks on that variable object. If it doesn't have one, it looks at the next link in the chain, and so on, and so on. And you know what the final link in the chain is, right? Right! The global object (window, on browsers).
Consider this code (assume we start in global scope; live copy):
var alpha = "I'm window.alpha";
var beta = "I'm window.beta";
// These, of course, reference the globals above
display("[global] alpha = " + alpha);
display("[global] beta = " + beta);
function foo(gamma) {
var alpha = "I'm alpha in the variable object for the call to `foo`";
newSection();
// References `alpha` on the variable object for this call to `foo`
display("[foo] alpha = " + alpha);
// References `beta` on `window` (the containing variable object)
display("[foo] beta = " + beta);
// References `gamma` on the variable object for this call to `foo`
display("[foo] gamma = " + gamma);
setTimeout(callback, 200);
function callback() {
var alpha = "I'm alpha in the variable object for the call to `callback`";
newSection();
// References `alpha` on the variable obj for this call to `callback`
display("[callback] alpha = " + alpha);
// References `beta` on `window` (the outermost variable object)
display("[callback] beta = " + beta);
// References `gamma` on the containing variable object (the call to `foo` that created `callback`)
display("[callback] gamma = " + gamma);
}
}
foo("I'm gamma1, passed as an argument to foo");
foo("I'm gamma2, passed as an argument to foo");
function display(msg) {
var p = document.createElement('p');
p.innerHTML = msg;
document.body.appendChild(p);
}
function newSection() {
document.body.appendChild(document.createElement('hr'));
}
The output is this:
[global] alpha = I'm window.alpha
[global] beta = I'm window.beta
--------------------------------------------------------------------------------
[foo] alpha = I'm alpha in the variable object for the call to `foo`
[foo] beta = I'm window.beta
[foo] gamma = I'm gamma1, passed as an argument to foo
--------------------------------------------------------------------------------
[foo] alpha = I'm alpha in the variable object for the call to `foo`
[foo] beta = I'm window.beta
[foo] gamma = I'm gamma2, passed as an argument to foo
--------------------------------------------------------------------------------
[callback] alpha = I'm alpha in the variable object for the call to `callback`
[callback] beta = I'm window.beta
[callback] gamma = I'm gamma1, passed as an argument to foo
--------------------------------------------------------------------------------
[callback] alpha = I'm alpha in the variable object for the call to `callback`
[callback] beta = I'm window.beta
[callback] gamma = I'm gamma2, passed as an argument to foo
You can see the scope chain at work there. During a call to callback, the chain is (top to bottom):
The variable object for that call to callback
The variable object for the call to foo that created callback
The global object
Note how the variable object for the call to foo lives on past the end of the foo function (foo returns before callback gets called by setTimeout). That's how closures work. When a function is created (note that a new callback function object is created each time we call foo), it gets an enduring reference to the variable object at the top of the scope chain as of that moment (the whole thing, not just the bits we see it reference). So for a brief moment while we're waiting our two setTimeout calls to happen, we have two variable objects for calls to foo in memory. Note also that arguments to functions behave exactly like vars. Here's the runtime of the above broken down:
The interpreter creates the global scope.
It creates the global object and populates it with its default set of properties (window, Date, String, and all the other "global" symbols you're used to having).
It creates properties on the global object for all var statements at global scope; initially they have the value undefined. So in our case, alpha and beta.
It creates properties on the global object for all function declarations at global scope; initially they have the value undefined. So in our case, foo and my utility functions display and newSection.
It processes each function declaration at global scope (in order, top to bottom):
Creates the function object
Assigns it a reference to the current variable object (the global object in this case)
Assigns the function object to its property on the variable object (again, the global object in this case)
The interpreter begins executing the step-by-step code, at the top.
The first line it reaches is var alpha = "I'm window.alpha";. It's already done the var aspect of this, of course, and so it processes this as a straight assignment.
Same for var beta = ....
It calls display twice (details omitted).
The foo function declaration has already been processed and isn't part of step-by-step code execution at all, so the next line the interpreter reaches is is foo("I'm gamma1, passed as an argument to foo");.
It creates an execution context for the call to foo.
It creates a variable object for this execution context, which for convenience I'll call foo#varobj1.
It assigns foo#varobj1 a copy of foo's reference to the variable object where foo was created (the global object in this case); this is its link to the "scope chain."
The interpreter creates properties on foo#varobj1 for all named function arguments, vars, and function declarations inside foo. So in our case, that's gamma (the argument), alpha (the var), and callback (the declared function). Initially they have the value undefined. (A few other default properties are created here that I won't go into.)
It assigns the properties for the function arguments the values passed to the function.
It processes each function declaration in foo (in order, beginning to end). In our case, that's callback:
Creates the function object
Assigns that function object a reference to the current variable object (foo#varobj1)
Assigns the function object to its property on foo#varobj1
The interpreter begins step-by-step execution of the foo code
It processes the assignment from the var alpha = ... line, giving foo#varobj1.alpha its value.
It looks up the free variable newSection and calls the function (details omitted, we'll go into detail in a moment).
It looks up the free variable alpha:
First it looks on foo#varobj1. Since foo#varobj1 has a property with that name, it uses the value of that property.
It looks up display and calls it (details omitted).
It looks up the free variable beta:
First it looks on foo#varobj1, but foo#varobj1 doesn't have a property with that name
It looks up the next link in the scope chain by querying foo#varobj1 for its reference to the next link
It looks on that next link (which happens to be the global object in this case), finds a property by that name, and uses its value
It calls display
It looks up gamma and calls display. This is exactly the same as for alpha above.
It looks up the free variable callback, finding it on foo#varobj1
It looks up the free variable setTimeout, finding it on the global object
It calls setTimeout, passing in the arguments (details omitted)
It returns out of foo. At this point, if nothing had a reference to foo#varobj1, that object could be reclaimed. But since the browser's timer stuff has a reference to the callback function object, and the callback function object has a reference to foo#varobj1, foo#varobj1 lives on until/unless nothing refers to it anymore. This is the key to closures.
Wash/rinse/repeat for the second call to foo, which creates foo#varobj2 and another copy of callback, assigning that second callback a reference to foo#varobj2, and ultimately passing that second callback to setTimeout and returning.
The interpreter runs out of step-by-step code to execute and goes into its event loop, waiting for something to happen
About 200 milliseconds go by
The browser's timer stuff tells the interpreter it needs to call the first callback function we created in foo
The interpreter creates an execution context and associated variable object (callback#varobj1) for the call; it assigns callback#varobj1 a copy of the variable object reference stored on the callback function object (which is, of course, foo#varobj1) so as to establish the scope chain.
It creates a property, alpha, on callback#varobj1
It starts step-by-step execution of callback's code
You know what happens next. It looks up various symbols and calls various functions:
Looks up newSection, which it doesn't find on callback#varobj1 and so looks at the next link, foo#varobj1. Not finding it there, it looks at the next link, which is the global object, and finds it.
Looks up alpha, which it finds on the topmost variable object, callback#varobj1
Looks up beta, which it doesn't find until it gets down to the global object
Looks up gamma, which it finds only one link down the scope chain on foo#varobj1
The interpreter returns from the call to callback
Almost certainly, there in its event queue there's a message from the browser waiting for it, telling it to call the second callback function, which we created in our second call to foo.
So it does it all again. This time, the variable object for the call to callback gets a reference to foo#varobj2 because that's what's stored on this particular callback function object. So (amongst other things) it sees the gamma argument we passed to the second call, rather than the first one.
Since the browser has now released its references to the two callback function objects, they and the objects they refer to (including foo#varobj1, foo#varobj2, and anything their properties point to, like gamma's strings) are all eligible for garbage collection.
Whew That was fun, eh?
One final point about the above: Note how JavaScript scope is determined entirely by the nesting of the functions in the source code; this is called "lexical scoping." E.g., the call stack doesn't matter for variable resolution (except in terms of when functions get created, because they get a reference to the variable object in scope when they were created), just the nesting in the source code. Consider (live copy):
var alpha = "I'm window.alpha";
function foo() {
var alpha = "I'm alpha in the variable object for the call to `foo`";
bar();
}
function bar() {
display("alpha = " + alpha);
}
foo();
What ends up getting output for alpha? Right! "I'm window.alpha". The alpha we define in foo has no effect whatsoever on bar, even though we called bar from foo. Let's quickly walk through:
Set up global execution context etc. etc.
Create properties for the vars and declared functions.
Assign alpha its value.
Create the foo function object, give it a reference to the current variable object (which is the global object), put it on the foo property.
Create the bar function object, give it a reference to the current variable object (which is the global object), put it on the bar property.
Call foo by creating an execution context and variable object. The variable object, foo#varobj1, gets a copy of foo's reference to its parent variable object, which is of course the global object.
Start step-by-step execution of foo's code.
Look up the free variable bar, which it finds on the global object.
Create an execution context for the call to bar and its associated variable object bar#varobj1. Assign bar#varobj1 a copy of bar's reference to its parent variable object, which is of course the global object.
Start step-by-step execution of bar's code.
Look up the free variable alpha:
First it looks on bar#varobj1, but there's no property with that name there
So it looks at the next link, which is the link it got from bar, which is the global object. So it finds the global alpha
Note how foo#varobj1 isn't linked at all to bar's variable object. And that's good, because we'd all go nuts if what was in scope was defined by how and from where a function was called. :-) Once you understand that it's linked to function creation, which is dictated by the nesting of the source code, it gets a lot easier to understand.
And that's why what's in scope for bar is determined entirely by where bar is in the source code, not how it got called at runtime.
It's not surprising that initially you were wondering about the relationship between this and variable resolution, because the global object (window) serves two unrelated purposes in JavaScript: 1. It's the default this value if a function isn't called in a way that sets a different one (and at global scope), and 2. It's the global variable object. These are unrelated aspects of what the interpreter uses with the global object for, which can be confusing, because when this === window, it seems like variable resolution relates in some way to this, but it doesn't. As soon as you start using something else for this, this and variable resolution are completely disconnected from one another.
Your understanding of properties and constructors is fine; the concepts you're missing are 'scopes' and 'closures'. This is where var comes into play.
Try reading Robert Nyman's explanation
You have some examples in this fiddle :
var x = 42;
function alertXs() {
this.x = 'not 42'; // this = window
var x = '42 not'; // local x
alert('window.x = ' + window.x); // 'not 42'
alert('this.x = ' + this.x); // 'not 42'
alert('x = ' + x); // '42 not'
}
alertXs();
http://jsfiddle.net/Christophe/Pgk73/
Sometimes, creating tiny fiddles helps to understand...
But you are aware with local and public variable as you explain that very well...

Categories

Resources