"Closure" in Javascript using object references: where are "private variables" stored? - javascript

Disclaimer: this may be a silly question, but it's something that has got me confused while studying Javascript.
I recently ran across the paradigmatic method to create private variables using closure in Javascript, namely using a function that returns an object that has reference to "private variables" through its methods
var safebox = function() {
var _privateVariable = "abcd";
return {
"accessFunction":function() {
return _privateVariable;
}
}();
safebox.accessFunction(); // "abcd"
That is to say, the mechanism of closure maintains the variable _privateVariable even after the enclosing function returns.
What happens if the private variable is an object to which a reference is maintained after the enclosing function returns?
var safebox = function () {
var _secretObject = {"secret": "abcd"}
return {referenceToSecretObject: _secretObject};
}();
console.log(safebox); // "abcd"
safebox.referenceToSecretObject.secret = "def";
console.log(safebox); // "def"
Here, as I understand it, ´_secretObject´ still exists, as we have a (shared) reference to it in ´safebox.referenceToSecretObject´. But this isn't closure (as I understand it). Is it just what it is, that the variable still exists because there is a reference to it (not garbage collected) even after the function returns? I am just confused because it seems close in form to closure, but perhaps I'm just seeing some resemblance that is purely coincidental.

Inside the function you have:
A variable _secretObject which has a value that is a reference to an object
A second object with a property referenceToSecretObject which has a reference to the same object
You are calling that function and assigning the return value (the second object) to safebox.
At this point the function finishes.
What happens if the private variable is an object to which a reference is maintained after the enclosing function returns?
The variable _secretObject drops out of scope. There is nothing that can access it. The variable is cleaned up. It no longer exists.
The object _secretObject used to reference still exists because the second object still references it (and the second object is referenced by safebox).
If you were to then, for example, safebox = null then the reference to the second object would go away.
This would leave 0 references to the second object so it would be garbage collected.
This would get rid of the referenceToSecretObject so there would be 0 references to the first object.
It is at this point that the first object would be garbage collected.

In Javascript there are not such things like private variables or private functions like in PHP. The underscore sign is only a convention.
You can play with the closures to kinda have a "private like variable". For instance :
function Foo(bar)
{
//bar is inside a closure now, only these functions can access it
this.setBar = function() {bar = 5;}
this.getBar = function() {return bar;}
//Other functions
}
var myFoo = new Foo(5);
console.log(myFoo.bar); //Undefined, cannot access variable closure
console.log(myFoo.getBar()); //Works, returns 5

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)

Can you get the property name through which a function was called?

I've done a lot of searching and some playing around, and I'm pretty sure the answer to this question is no, but I'm hoping a JavaScript expert might have a trick up his sleeve that can do this.
A JavaScript function can be referenced by multiple properties, even on completely different objects, so there's no such thing as the object or property that holds the function. But any time you actually call a function, you must have done so via a single object (at the very least, the window object for global function calls) and property on that object.
(A function can also be called via a function-local variable, but we can consider the function-local variable to be a property of the activation object of the scope, so that case is not an exception to this rule.)
My question is, is there a way to get that property name that was used to call the function, from inside the function body? I don't want to pass in the property name as an argument, or closure around a variable in an enclosing scope, or store the name as a separate property on the object that holds the function reference and have the function access that name property on the this object.
Here's an example of what I want to do:
var callName1 = function() { var callName = /* some magic */; alert(callName); };
var obj1 = {'callName2':callName1, 'callName3':callName1 };
var obj2 = {'callName4':callName1, 'callName5':callName1 };
callName1(); // should alert 'callName1'
obj1.callName2(); // should alert 'callName2'
obj1.callName3(); // should alert 'callName3'
obj2.callName4(); // should alert 'callName4'
obj2.callName5(); // should alert 'callName5'
From my searching, it looks like the closest you can get to the above is arguments.callee.name, but that won't work, because that only returns the name that was fixed to the function object when it was defined, and only if it was defined as a named function (which the function in my example is not).
I also considered that maybe you could iterate over all properties of the this object and test for equality with arguments.callee to find the property whose value is a reference to the function itself, but that won't work either (in the general case), because there could be multiple references to the function in the object's own (or inherited) property set, as in my example. (Also, that seems like it would be kind of an inefficient solution.)
Can this be done?
Short answer:
No, you cannot get "the property name" used to call your function.
There may be no name at all, or multiple names across different scopes, so "the property name" is pretty ill defined.
arguments.callee is deprecated and should not be used.
There exists no solution that does not use arguments or closure.
Long answer:
As thefourtheye commented, you should rethink what you are trying to do and ask that instead in a new question. But there are some common misconceptions, so I will try to explain why you cannot get the "simple property name".
The reason is because it is not simple.
Before we go ahead, let us clarify something. Activation Objects are not objects at all.
The ECMAScript 5.1 specification calls them Environment Records (10.2.1), but a more common term is Scope chain.
In a browser the global scope is (often) the window object, but all other scopes are not objects.
There may be an object that you use to call a function, and when you call a function you must be in some scope.
With few exceptions, scopes are not objects, and objects are not scopes.
Then, there are many names.
When you call a function, you need to reference it, such as through an object property. This reference may have a name.
Scope chain has declarations, which always have a name.
A Function (the real function, not reference) may also have a function name - your arguments.callee.name - which is fixed at declaration.
Not only are they different names, they are not (always) the "the property name" you are seeking.
var obj = { prop : function f(){} }, func = obj.prop;
// "obj" and "func" are declarations.
// Function name is "f" - use this name instead of arguments.callee
// Property name is "prop"
func(); // Reference name is "func"
obj.prop(); // Reference names are "obj" and "prop"
// But they are the same function!
// P.S. "this" in f is undefined (strict mode) or window (non-strict)
So, a function reference may comes from a binding (e.g. function declaration), an Object (arguments.callee), or a variable.
They are all References (8.7). And reference does have a name (so to speak).
The catch is, a function reference does not always come from an object or the scope chain, and its name is not always defined.
For example a common closure technique:
(function(i){ /* what is my name? */ })(i)
Even if the reference does have a name, a function call (11.2.3) does not pass the reference or its name to the function in any way.
Which keeps the JavaScript engine sane. Consider this example:
eval("(new Function('return function a(){}'))()")() // Calls function 'a'.
The final function call refers the eval function, which refers the result of a new global scope (in strict mode, anyway), which refers a function call statement, which refers a group, which refers an anonymous Function object, and which contains code that expresses and returns a function called 'a'.
If you want to get the "property name" from within a, which one should it get? "eval"? "Function"? "anonymous"? "a"? All of them?
Before you answer, consider complications such as function access across iframes, which has different globals as well as cross origin restriction, or interaction with native functions (Function.prototype.bind for example), and you will see how it quickly becomes hell.
This is also why arguments.caller, __caller__, and other similar techniques are now all deprecated.
The "property name" of a function is even more ill defined than the caller, almost unrealistic.
At least caller is always an execution context (not necessary a function).
So, not knowing what your real problem is, the best bet of getting the "property name" is using closure.
there is no reflection, but you can use function behavior to make adding your own fairly painless, and without resorting to try/catch, arguments.callee, Function.caller, or other strongly frowned-upon behavior, just wasteful looping:
// returning a function from inside a function always creates a new, unique function we can self-identify later:
function callName() {
return function callMe(){
for(var it in this) if(this[it]===callMe) return alert(it);
}
};
//the one ugly about this is the extra "()" at the end:
var obj1 = {'callName2':callName(), 'callName3':callName() };
var obj2 = {'callName4':callName(), 'callName5':callName() };
//test out the tattle-tale function:
obj1.callName2(); // alerts 'callName2'
obj2.callName5(); // alerts 'callName5'
if you REALLY want to make it look like an assignment and avoid the execution parens each time in the object literal, you can do this hacky routine to create an invoking alias:
function callName() {
return function callMe(){
for(var it in this) if(this[it]===callMe) return alert(it);
}
};
//make an alias to execute a function each time it's used :
Object.defineProperty(window, 'callNamer', {get: function(){ return callName() }});
//use the alias to assign a tattle-tale function (look ma, no parens!):
var obj1 = {'callName2': callNamer, 'callName3': callNamer };
var obj2 = {'callName4': callNamer, 'callName5': callNamer };
//try it out:
obj1.callName2(); // alerts 'callName2'
obj2.callName5(); // alerts 'callName5'
all that aside, you can probably accomplish what you need to do without all the looping required by this approach.
Advantages:
works on globals or object properties
requires no repetitive key/name passing
uses no proprietary or deprecated features
does not use arguments or closure
surrounding code executes faster (optimized) than
a try/catch version
is not confused by repeated uses
can handle new and deleted (renamed) properties
Caveats:
doesn't work on private vars, which have no property name
partially loops owner object each access
slower computation than a memorized property or code-time repetition
won't survive call/bind/apply
wont survive a setTimeout without bind() or a wrapper function
cannot easily be cloned
honestly, i think all the ways of accomplishing this task are "less than ideal", to be polite, and i would recommend you just bite the coding bullet and pass extra key names, or automate that by using a method to add properties to a blank object instead of coding it all in an object literal.
Yes.
Sort Of.
It depends on the browser. (Chrome=OK, Firefox=Nope)
You can use a factory to create the function, and a call stack parsing hack that will probably get me arrested.
This solution works in my version of Chrome on Windows 7, but the approach could be adapted to other browsers (if they support stack and show the property name in the call stack like Chrome does). I would not recommend doing this in production code as it is a pretty brittle hack; instead improve the architecture of your program so that you do not need to rely on knowing the name of the calling property. You didn't post details about your problem domain so this is just a fun little thought experiment; to wit:
JSFiddle demo: http://jsfiddle.net/tv9m36fr/
Runnable snippet: (scroll down and click Run code snippet)
function getCallerName(ex) {
// parse the call stack to find name of caller; assumes called from object property
// todo: replace with regex (left as exercise for the reader)
// this works in chrome on win7. other browsers may format differently(?) but not tested.
// easy enough to extend this concept to be browser-specific if rules are known.
// this is only for educational purposes; I would not do this in production code.
var stack = ex.stack.toString();
var idx = stack.indexOf('\n');
var lines = ex.stack.substring(idx + 1);
var objectSentinel = 'Object.';
idx = lines.indexOf(objectSentinel);
var line = lines.substring(idx + objectSentinel.length);
idx = line.indexOf(' ');
var callerName = line.substring(0, idx);
return callerName;
}
var Factory = {
getFunction: function () {
return function () {
var callName = "";
try {
throw up; // you don't *have* to throw to get stack trace, but it's more fun!
} catch (ex) {
callName = getCallerName(ex);
}
alert(callName);
};
}
}
var obj1 = {
'callName2': Factory.getFunction(),
'callName3': Factory.getFunction()
};
var obj2 = {
'callName4': Factory.getFunction(),
'callName5': Factory.getFunction()
};
obj1.callName2(); // should alert 'callName2'
obj1.callName3(); // should alert 'callName3'
obj2.callName4(); // should alert 'callName4'
obj2.callName5(); // should alert 'callName5'

"this" as scope limiter?

I'm trying to understand "this" and everything I've looked at talks about context. What this has led me to is the idea that "this" is a scope limiter. It makes sure your variables are referenced using the proper scope, mostly by keeping variables "local" -ish in scope, and keeping them from reaching too far out from where the running code is.
My question is: is that correct? I tried to do searches using the concept I'm trying to get across, but those came up with totally bad results. There is a lot of nuance with "this", and from the reading I've done, I feel like this is a better explanation than what I've seen, but I want to make sure I'm correct in that thinking.
this and variable scope are separate concepts. Variable scope refers to which variables can be accessed from where within your application. Just because you wrote var foo somewhere doesn't mean that you can access it from everywhere throughout your codebase. In Javascript each function introduces a new scope, and scopes nest in a way that inner functions have access to the scope of outer functions, but not vice versa.
this on the other hand is simply a "magic" reference to the "current" object. Maybe it's helpful to explain this idea in the context of other, classical languages first:
class Foo {
protected $bar;
public function baz() {
echo $this->bar;
}
}
In PHP the magic keyword $this refers to the current object instance. Each time you call new Foo, a new instance of this class is created. Every time you call $foo->baz(), the same function is executed, though with $this set to the appropriate object instance so each object instance can access its own data.
In Python this is actually a lot more explicit:
class Foo:
def baz(self):
print self.bar
Python does not have a magic keyword to refer to the current object instance. Instead, every method call on an object gets the current object passed explicitly as its first argument. This is typically named self. If Python seems too alien to you, the above in PHP syntax would be:
class Foo {
public function baz($this) {
echo $this->bar;
}
}
Technically the functions in those classes do not really "belong" to any "class". They're just functions. You just need some way for those functions to be able to refer to a polymorphic object in order for them to be instance methods. Take for example:
function baz($obj) {
echo $obj->baz;
}
That's essentially exactly the same as what the class method does above, with the difference being that $obj is explicitly injected instead of $this being magically "there".
Javascript has the same thing, except that this is available in every function (not just "class" functions) and that the object this points to can be freely changed at runtime. this is simply a magic keyword that points to an object, period.
function Foo() {
this.bar = null;
this.baz = function () {
console.log(this.bar);
}
}
When calling regular functions on objects like foo.baz(), this typically refers to foo inside of baz(); though it really doesn't have to:
foo.baz.apply(someOtherObj);
This takes the function foo.baz and calls it while setting the this keyword inside baz to someOtherObj. It freely re-associates the function with another object instance, if you will. But only because the only thing that "bound" the function to the object in the first place was the this keyword anyway. The function will still simply do console.log(this.bar), whatever this.bar refers to.
A more complete example:
function Foo() {
this.bar = 'baz';
}
Foo.prototype.speak = function () {
alert(this.bar);
};
var o = new Foo();
o.speak(); // alerts 'baz'
alert(o.bar); // also alerts 'baz'
var o2 = { bar : 42 };
o.speak.apply(o2); // alerts 42
As you can see, this doesn't limit the scope of anything. What's happening here?
The Foo constructor is called with new Foo(). new simply creates a new object and executes Foo() with this set to this new object. Basically:
var tmp = {}; // tmp does not *actually* exist,
// that's more or less what `new` does behind the scenes
Foo.apply(tmp);
The Foo constructor assigns the bar property of that new object.
tmp.bar = 'baz';
The new object is assigned to o.
var o = tmp;
o.speak() is a function bound to that object through its prototype. Calling it as o.speak(), this inside speak() refers to the o object. Because that object has a property bar, this works.
Notice that it's also possible to do alert(o.bar). The .bar property was set on this originally, then this became o. So o has the property .bar, which is a regular property of the object. It's not scope limited or anything.
Next, we simply create another object o2, which also happens to have a bar property. Then we call o.speak, but we explicitly override the choice of what this refers to using apply. We simply do a switcheroo on what object the this keyword refers to. Thereby the speak function alerts the bar property of the o2 object.
As you see (hopefully, I know this can be brain bending at first), this is nothing more and nothing less than a reference to an object. That's all. It doesn't limit at all the scope of anything. functions limit scopes, this is just an arbitrary object. Anything you set on this is not limited in scope; on the contrary, it's always publicly accessible from anywhere you have access to the object.
It's incredible how trivial it all is once you manage to wrap your head around it. this refers to an object, it is simply Javascript's magic keyword to refer to an object. There are certain trivial rules which object it refers to at any given time, but all those can be bend and broken and reassigned. An object is simply a thing with properties. The properties can be functions. Only functions limit variable scope. That's pretty much all there is to it. Don't try to interpret anything else into this.

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.

But var it is not for local variable?

This is my code :
var markers={};
example();
function example() {
var myFunct = function () {
alert("hello");
};
markers["myIndex"] = myFunct;
}
markers["myIndex"]();
as you can see, myFunct is "var" (so, when example() finish, it will be destroyed, because it is local). But in fact, accessing to markers["myIndex"](), the function is referenced, and I can access to it. Why?
This doesn't work the way you expect it to. In other words, when example() finishes, myFunct will not be destroyed because there is still a reference to that function in a variable from an outer scope, markers.
The only way it would be 'destroyed' is if nothing else referenced it at the end of example() or if only variables with equal or lower scope referenced it, provided those variables also followed the same rules and were not referenced from outer variables.
In JavaScript, functions are objects just like other objects. When you do this:
var myFunct = function () {
alert("hello");
};
...you're creating a function and assigning a reference to that function to the variable myFunct. Then when you do this:
markers["myIndex"] = myFunct;
...you're assigning another reference to that function to markers["myIndex"]. So regardless of anything else that might happen to the myFunct variable, because markers["myIndex"] still has a reference to the function, the function is kept in memory.
But separately, there's a more subtle misunderstanding in your question as well: You've said:
myFunct is "var" (so, when example() finish, it will be destroyed, because it is local)
That's not true in JavaScript. In JavaScript, local variables are actually properties of a hidden object, called (deep breath) the variable binding object of the execution context (let's just call it the "variable object"). This object is associated with the particular call to example: It's created when the call to example is executed. Now, in the normal course of things, when example returns, if nothing has any outstanding reference to the variable object, then you're quite correct that it is eligible for garbage collection. But in your case, something does have a reference to the variable object: The function you created. When you create a function, it receives an implicit reference to the variable object for the context in which it was created, and it keeps that reference for as long as the function exists. So even though the function you're creating doesn't refer to anything in the variable object for the call to example, it has that reference to it nevertheless, and the variable object cannot be reclaimed until or unless nothing has a reference to the function anymore. This is how closures work. The foregoing text notwithstanding, closures are not complicated, they're really, really simple when you understand how they work.
(I'll just note here that some JavaScript engines introspect the code sufficiently that they can reclaim variable objects even when there are outstanding closures that refer to them. Specifically, if the closures [functions] don't actually use any of the variable object's properties, and they don't use eval, then the engine may be able to release the variable object. Chrome's V8 engine does this, for instance. But that's a runtime optimization; the concept is as described above.)
Because you have assigned it to the global variable markers from within your example function.
you're assigning a reference to the function object to a higher scope (if not global scope) object. So while myFunct would be garbage collected, the function is not, since there is another reference to it in the markers object.
A reference from var myFunct to the actual function object (function() { ... }) will indeed be destroyed. But the object itself will not, as it is referenced by a markers field. Once there are no live references to the function object from live JS objects, this function object will be eligible for garbage collection.

Categories

Resources