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.
Related
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
I'm a beginner to closures (and Javscript in general), and I can't find a satisfactory explanation as to what's going on in this code:
function myObject(){
this.myHello = "hello";
this.myMethod = do_stuff;
}
function do_stuff(){
var myThis = this;
$.get('http://example.com', function(){
alert(this.myHello);
alert(myThis.myHello);
});
}
var obj = new myObject;
obj.myMethod();
It will alert 'undefined' and then 'hello'. Obviously this should not be jQuery specific, but this is the simplest form of my original code I could come up with. The closure in do_stuff() has access to the variables in that scope, but apparently this rule does not apply to the this keyword.
Questions:
What happens to this when the closure is passed outside the scope of do_stuff() (in this case $.get())? Does myThis contain a copy of this or a reference to it? Is it generally not a good idea to use this in closures?
Any response much appreciated.
What happens to this when the closure is passed outside the scope of do_stuff() (in this case $.get())?
Each function has its own execution context, the this keyword retrieves the value of the current context.
The doStuff identifier and the obj.myMethod property refer to the same function object, but since you are invoking it as a property of an object (obj.myMethod();), the this value inside that function, will refer to obj.
When the Ajax request has succeeded, jQuery will invoke the second function (starting a new execution context), and it will use an object that contains the settings used for the request as the this value of that callback.
Does myThis contain a copy of this or a reference to it?
The myThis identifier will contain a reference to the object that is also referenced by the this value on the outer scope.
Is it generally not a good idea to use this in closures?
If you understand how the this value is handled implicitly, I don't see any problem...
Since you are using jQuery, you might want to check the jQuery.proxy method, is an utility method that can be used to preserve the context of a function, for example:
function myObject(){
this.myHello = "hello";
this.myMethod = do_stuff;
}
function do_stuff(){
$.get('http://example.com', jQuery.proxy(function(){
alert(this.myHello);
}, this)); // we are binding the outer this value as the this value inside
}
var obj = new myObject;
obj.myMethod();
See also:
‘this’ object can’t be accessed in private JavaScript functions without a hack?
$.get('http://example.com', function(){
alert(this.myHello); // this is scoped to the function
alert(myThis.myHello); // myThis is 'closed-in'; defined outside
});
note the anonymous function. this in that scope is the scope of the function. myThis is the this of the outer scope, where the myHello has been defined. Check it out in firebug.
'this' always refers to the current scope of execution, i believe. If you want to take the current scope and preserve it, you do what you did, which is assign this to another variable.
$.get('http://example.com', function(){
// inside jQuery ajax functions - this == the options used for the ajax call
});
What happens to this when the closure is passed outside the scope of do_stuff() (in this case $.get())?
Nothing "happens" to it, this is still this for that closure, the execution context of the functions called from the closure do not automatically inherit this.
Does myThis contain a copy of this or a reference to it?
All non-scalar assignments are references in JavaScript. So it is a reference to this, if you change properties on either, they change for both.
Is it generally not a good idea to use this in closures?
It is generally a good idea to use this in closures, but if you're going to be using closures inside that need to access the same this, its good practice to do exactly what you did: var someName = this; and then access using someName
I now know this works:
function outerfunction(arg1, arg2, arg3) {
var others;
//Some code
innerFunction();
function innerFunction() {
//do some stuff
//I have access to the args and vars of the outerFunction also I can limit the scope of vars in the innerFunction..!
}
//Also
$.ajax({
success : secondInnerFunction;
});
function secondInnerFunction() {
// Has all the same benefits!
}
}
outerFunction();
So, I am not doing a 'new' on the outerFunction, but I am using it as an object! How correct is this, semantically?
There doesn't appear to be anything wrong with what you're doing. new is used to construct a new object from a function that is intended as a constructor function. Without new, no object is created; the function just executes and returns the result.
I assume you're confused about the closure, and how the functions and other variables belonging to the function scope are kept alive after the function exits. If that's the case, I suggest you take a look at the jibbering JavaScript FAQ.
You are not using the outer function as an object. You are using it to provide a closure. The border line is, admittedly, thin, but in this case, you are far away from objects, since you do not pass around any kind of handle to some more generic code invoking methods, all you do is limiting the scope of some variables to the code that needs to be able to see them.
JFTR, there is really no need to give the outer function a name. Just invoke it:
(function() { // just for variable scoping
var others;
...
})()
I do this sort of thing all the time. Yes - javascript blurs the boundary between objects and functions somewhat. Or perhaps, more correctly, a javascript function is just an object that is callable. You would only really use the 'new' prefix if you wanted to have multiple instances of the function. My only suggestion here is that its usually considered good practice to call a function after you've declared it (you are calling the innerFunction before it has been declared) - although that could be considered nit-picking.
This is a valid example.
Functions in JavaScript are first order objects. They can be passed as an argument, returned from a function or even set to a variable. Therefore they are called 'lambda'.
So when you are directly using this function (without new keyword) you are directly dealing with the function as an object. When u are using new keyword, you are dealing with an object instance of the function.
I'm a beginner to closures (and Javscript in general), and I can't find a satisfactory explanation as to what's going on in this code:
function myObject(){
this.myHello = "hello";
this.myMethod = do_stuff;
}
function do_stuff(){
var myThis = this;
$.get('http://example.com', function(){
alert(this.myHello);
alert(myThis.myHello);
});
}
var obj = new myObject;
obj.myMethod();
It will alert 'undefined' and then 'hello'. Obviously this should not be jQuery specific, but this is the simplest form of my original code I could come up with. The closure in do_stuff() has access to the variables in that scope, but apparently this rule does not apply to the this keyword.
Questions:
What happens to this when the closure is passed outside the scope of do_stuff() (in this case $.get())? Does myThis contain a copy of this or a reference to it? Is it generally not a good idea to use this in closures?
Any response much appreciated.
What happens to this when the closure is passed outside the scope of do_stuff() (in this case $.get())?
Each function has its own execution context, the this keyword retrieves the value of the current context.
The doStuff identifier and the obj.myMethod property refer to the same function object, but since you are invoking it as a property of an object (obj.myMethod();), the this value inside that function, will refer to obj.
When the Ajax request has succeeded, jQuery will invoke the second function (starting a new execution context), and it will use an object that contains the settings used for the request as the this value of that callback.
Does myThis contain a copy of this or a reference to it?
The myThis identifier will contain a reference to the object that is also referenced by the this value on the outer scope.
Is it generally not a good idea to use this in closures?
If you understand how the this value is handled implicitly, I don't see any problem...
Since you are using jQuery, you might want to check the jQuery.proxy method, is an utility method that can be used to preserve the context of a function, for example:
function myObject(){
this.myHello = "hello";
this.myMethod = do_stuff;
}
function do_stuff(){
$.get('http://example.com', jQuery.proxy(function(){
alert(this.myHello);
}, this)); // we are binding the outer this value as the this value inside
}
var obj = new myObject;
obj.myMethod();
See also:
‘this’ object can’t be accessed in private JavaScript functions without a hack?
$.get('http://example.com', function(){
alert(this.myHello); // this is scoped to the function
alert(myThis.myHello); // myThis is 'closed-in'; defined outside
});
note the anonymous function. this in that scope is the scope of the function. myThis is the this of the outer scope, where the myHello has been defined. Check it out in firebug.
'this' always refers to the current scope of execution, i believe. If you want to take the current scope and preserve it, you do what you did, which is assign this to another variable.
$.get('http://example.com', function(){
// inside jQuery ajax functions - this == the options used for the ajax call
});
What happens to this when the closure is passed outside the scope of do_stuff() (in this case $.get())?
Nothing "happens" to it, this is still this for that closure, the execution context of the functions called from the closure do not automatically inherit this.
Does myThis contain a copy of this or a reference to it?
All non-scalar assignments are references in JavaScript. So it is a reference to this, if you change properties on either, they change for both.
Is it generally not a good idea to use this in closures?
It is generally a good idea to use this in closures, but if you're going to be using closures inside that need to access the same this, its good practice to do exactly what you did: var someName = this; and then access using someName
Does JavaScript support garbage collection?
For example, if I use:
function sayHello (name){
var myName = name;
alert(myName);
}
do I need to use "delete" to delete the myName variable or I just ignore it?
no.
delete is used to remove properties from objects, not for memory management.
JavaScript supports garbage collection. In this case, since you explicitly declare the variable within the function, it will (1) go out of scope when the function exits and be collected sometime after that, and (2) cannot be the target of delete (per reference linked below).
Where delete may be useful is if you declare variables implicitly, which puts them in global scope:
function foo()
{
x = "foo"; /* x is in global scope */
delete x;
}
However, it's a bad practice to define variables implicitly, so always use var and you won't have to care about delete.
For more information, see: https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Special_Operators/delete_Operator
Ignore it - after the sayHello function completes, myName falls out-of-scope and gets gc'ed.
You don't need to do anything Ted, no need to delete this variable.
Refer: http://www.codingforums.com/archive/index.php/t-157637.html
As others mentioned, when the function exits then your variable falls out of scope, as it's scope is just within the function, so the gc can then clean it up.
But, it is possible for that variable to be referenced by something outside the function, then it won't be gc'ed for a while, if ever, as it is still has a reference to it.
You may want to read up on scoping in javascript:
http://www.webdotdev.com/nvd/content/view/1340/
With closures you can create memory leaks, which may be the problem you are trying to deal with, and is related to the problem I had mentioned:
http://www.jibbering.com/faq/faq_notes/closures.html