Are these javascript closures? - javascript

Refering to How do JavaScript closures work?.
Closure is:
a closure is the local variables for a function — kept alive after the function has returned, or
a closure is a stack-frame which is not deallocated when the function returns (as if a 'stack-frame' were malloc'ed instead of being on the stack!).
Just want to confirm are the following consider closure?
1) Binding javascript function within a function.
var Books = {
init:function(){
$('#box').bind('click',function(){
console.log('click');
});
}
};
Books.init();​
2) Declare a function within a function
function sayHello(name) {
var text = 'Hello ' + name;
var sayAlert = function() { alert(text); }
}
var hello = sayHello();
I still can't differentiate which is closure for some times, is that all function within function consider closure or only the one that keep the returned inner function as variable/reference. Example:
function sayHello(name) {
var text = 'Hello ' + name;
var sayAlert = function() { alert(text); }
**return sayAlert;**
}

1 isn't as no variables are actually referenced, 2 and 3 are.
In 2 and 3 the variable called text is closed off - referenced outside its lexical scope. In 1 nothing is.
crockford on closures :
What this means is that an inner function always has access to the
vars and parameters of its outer function, even after the outer
function has returned.

All of those are closures.
I'm not sure what your confusion is.

Related

Javascript Closure called automatically vs manually

I'm confused between these two closure functions.
The doSomeMath returns the function without executing it when I assigned it to a variable, test. It will only run the closure function when I do test();
However this is not the case for showName function. As soon as I pass in the values, it calls the closure function right away instead of returning it.
Can someone kindly explain it to me? Thanks.
function showName (firstName, lastName) {
var nameIntro = "Your name is ";
// this inner function has access to the outer function's variables, including the parameter
function makeFullName () {
var full = nameIntro + firstName + " " + lastName;
return full;
}
return makeFullName ();
}
showName ("Michael", "Jackson"); // Your name is Michael Jackson
function doSomeMath(a, b) {
var a = a;
var b = b;
function multiply() {
var result = a * b;
return result;
}
return multiply;
}
var test = doSomeMath(5,10);
test();
These two functions are two different ways of demonstrating how closures work.
You could as easily have done the opposite to achieve the same effect.
function doSomeMath(a, b) {
var a = a;
var b = b;
function multiply() {
var result = a * b;
return result;
}
return multiply();
}
doSomeMath(5,10) //50
In the above code you return the result of invocation of the inner function instead of the function itself. Here, as you can see, multiply has a closure over 5 and 10 and so you get the outcome as 50.
Similarly, try:
function showName (firstName, lastName) {
var nameIntro = "Your name is ";
// this inner function has access to the outer function's variables, including the parameter
function makeFullName () {
var full = nameIntro + firstName + " " + lastName;
return full;
}
return makeFullName;
}
var show = showName ("Michael", "Jackson");
show() //"Your name is Michael Jackson"
The above code returns the inner function instead of its invocation and in turn demonstrates how the inner function, makeFullName has a closure over the nameIntro variable of the outer function.
The other answer provides a concise understanding on closures. To know more read up on closures to understand the above examples better.
I think you are confusing closures and higher order functions.
There is no such concept as manually calling a function. A function must always be called. This does not change if the function is a closure.
In fact one might say that this is the essential power of closures as an abstraction mechanism.
A closure is a function that references elements in its enclosing scope.
This is often referred to as lexical scoping.
The set of elements of the enclosing scope that are referenced by a closure are known as its environment.
A function that does not refer to elements in its enclosing scope can be thought of as a degenerate closure - a closure with an empty environment.
The value returned by a function may be another function but this is purely orthogonal to the notion of closures.
In JavaScript, as in many languages, functions are first class values. This means that they can be stored in variables, passed as arguments, and returned as results.
Consider
var createIncrement = function (incrementBy) {
return function (value) {
return value + incrementBy;
};
};
The function above is higher order, because it returns a function. Incidentally, it is also a closure because it references incrementBy which is declared in an enclosing scope.
The confusion expressed in the framing of your question likely arises from the fact that, in practice, the two features will be used together in even the simplest of JavaScript programs.

Access to variables in scope from a function defined externally

Is there a way to print the value of temp (a closure variable) from a function defined outside the closure but referenced within the closure without passing temp as a variable to funcA?
var funcA, funcB;
funcA = function () {
console.log(temp);
}
funcB = function () {var temp, funcC;
temp = 1;
funcC = funcA;
funcC();
}
funcB(); // temp is undefined.
This works, but only because funcA is defined within funcB:
funcB = function () {var temp, funcA, funcC;
temp = 1;
funcA = function () {
console.log(temp);
}
funcC = funcA;
funcC();
}
funcB(); // 1
I'm trying to find a way to pull some function definitions out of outer functions to streamline code that's getting a little complex. Can I define funcA outside of funcB but still reference the temp variable without having to pass parameters?
I read that javascript does not have dynamic run time scoping, that it's only lexical scoping, but with referencing a function (funcA via funcC) within funcB, is there a way to meet the lexical scope requirement and provide access to the scoped variables for funcB?
Using Akinkunle Allen's comment, I came up with this which seems to solve my problem.
function funcB () {
var funcA, funcB, temp;
funcA = function () {
console.log(temp);
}
funcB = function () {var funcC;
temp = 1;
funcC = funcA;
funcC();
}
return funcB();
}
funcB(); // 1
Yes, and No.
The keyword var for declaring variables behaves different depending upon what the current scope is. When var is executed on the global scope it is optional. The variable becomes a property of the global object. When executing in the browser this global object is window.
So the following in global space has the same result.
var temp = 1;
window.temp = 1;
this.temp = 1;
All the above is just window.temp because of the global context.
When you use var inside a function then the variable is attached to the function. All functions in Javascript are objects so local var variables will live as long as the parent function is still being used somewhere.
Javascript will walk the hierarchy of executing scopes to find a variable identifier. So any inner functions can access their outer function variables (as in your example).
What you can do is play around with the this reference in functions.
The identifier this in Javascript is dynamic (meaning that you can change it). I can pass a variable to an unknown function that was declared outside the calling function. Since the this.temp is used to reference the variable the function funcA is able to display the value.
funcB = function(otherFunc)
{
this.temp = 1;
otherFunc();
}
funcA = function()
{
alert(this.temp);
}
funcB(funcA);
http://jsfiddle.net/thinkingmedia/dfLvj/
See the above jsfiddle example.
What you can do with this is change the meaning of this on the fly. Here is a better example.
funcB = function(otherFunc)
{
var temp = {
message: "Hello World!"
};
var foo = otherFunc.bind(temp);
foo();
}
funcA = function()
{
alert(this.message);
}
funcB(funcA);
http://jsfiddle.net/thinkingmedia/K5Pw6/
Dynamically changing this can have a lot of benefits by allowing a function to accept closure references that will be executed with a custom this reference.
An example might be a click event handler where this is the DOM element that triggered the event.

JavaScript: create a function within a specific scope

JavaScript: I need create a function within a specific scope.
The function to be created, is generated dynamically by a previous process of code generation. And the scope for the definition of this function may also change.
Look this example:
var createFnInOtherScope = function() {
console.debug('createFnInOtherScope: Who I am', this);
//This code can not be modified because it's dynamically generated
function MyFunction() {
console.debug('MyFunction');
}
}
var obInitial = {
createFn: function() {
console.debug('createFn: Who I am', this);
createFnInOtherScope.call(window);
}
}
obInitial.createFn();
//ReferenceError: MyFunction is not defined
window.MyFunction();
How I can do this?
Thanks.
If I understand you correctly, what you're asking is impossible.
Scope in Javascript is a lexical construct, meaning that what's in scope is defined by its physical location (at parse time) in the source file with respect to any enclosing functions.
You can't retrospectively add something into a scope once that scope has (lexically) been closed off.
Function scope is defined at parse time. You can create a function and make it visible as a window property:
function outer() {
function inner() {
console.log("hello world");
}
window.inner = inner;
}
window.inner(); // hello world
But that does not alter the scope of the "inner" function. It's visible and callable via the global object, but the function is unalterably in the scope of that "outer" function.
Just define this function in this context:
var createFnInOtherScope = function() {
this.MyFunction = function() {
console.debug('MyFunction');
};
};
DEMO: http://jsfiddle.net/Ur6vF/

closures in javascript understanding example [duplicate]

This question already has answers here:
How do JavaScript closures work?
(86 answers)
Closed 8 years ago.
function setupSomeGlobals() {
// Local variable that ends up within closure
var num = 666;
// Store some references to functions as global variables
gAlertNumber = function() {console.log(1); alert(num); }
gIncreaseNumber = function() { num++; }
gSetNumber = function(x) { num = x; }
}
how can I accesss here gAlertNumber method?
update: this code is the Example 4 in an answer on How do JavaScript closures work?
Assuming you're in a web browser, you have to execute setupSomeGlobal() first.
Then your non-declared handler variables g... will be created under the global object window and you'll be able to execute gAlertNumber() from anywhere in your page.
You could execute setupSomeGlobal() in the body's onload :
<html>
<head>
<script>
function setupSomeGlobals() {
// Local variable that ends up within closure
var num = 666;
// Store some references to functions as global variables
gAlertNumber = function() {console.log(1); alert(num); }
gIncreaseNumber = function() { num++; }
gSetNumber = function(x) { num = x; }
}
</script>
</head>
<body onload="setupSomeGlobals();">
<input type="button" value="Show me more or less the number of the beast" onclick="gAlertNumber();"
</body>
</html>
That said, your method of setting up "global" functions isn't very pretty.
I quite like the pattern described here for example.
Here is an example,
(function() {
console.log(1);
// Local variable that ends up within closure
var num = 666;
var sayAlert = function() { console.log(num); }
num++;
return sayAlert();
})();
This will call immediately after definition.
So with your code,
function setupSomeGlobals() {
var num = 666;
// Store some references to functions as global variables
gAlertNumber = function() {console.log(1); alert(num); }
gIncreaseNumber = function() { num++; }
gSetNumber = function(x) { num = x; }
gAlertNumber();
}
setupSomeGlobals();
Here you can call the child function gAlertNumber() inside your parent function setupSomeGlobals() and you cannot access it outside the parent function.
But you can call this after calling parent function, that means don't call the gAlertNumber() inside parent function. call it after calling parent like,
function setupSomeGlobals() {
// Local variable that ends up within closure
var num = 666;
// Store some references to functions as global variables
gAlertNumber = function() {console.log(1); alert(num); }
gIncreaseNumber = function() { num++; }
gSetNumber = function(x) { num = x; }
}
setupSomeGlobals();
gAlertNumber();
Return an object from setSomeGlobals() that contains the three methods. Through this object you will be able to access the functions of interest and manipulate num and keep its state, but you will not be able to access num directly. This is known as the module pattern, an application of closure.
Well this will work in browser
gAlertNumber is considered being window property.. It would be the same as calling
window.gAlertNumber()
so inside your setSomeGlobals you assign function object to the undefined window property. Than you close the local variable num inside that object which is already created inside window object. Thus you can access it from window scope.

Output of this javascript and the reason

function getCtr(){
var i = 0;
return function(){
console.log(++i);
}
}
var ctr = getCtr();
ctr();
ctr();
I've been using Javascript from last five years, but this question made me dumb in last interview. I tried everything to my knowledge but can't figure it out.
Can you please help me with the output and reason for it so that I can be better equipped for future interviews if I have one.
var ctr = getCtr();
This calls getCtr(), which initializes i to 0, and stores a reference to the function
function() {
console.log(++i)
}
in ctr. Because that function was created in the scope of getCtr(), the variable i is still accessible in the scope of the function stored in ctr.
The first call to
ctr()
executes console.log(++i) which has a preincrement on i, so it prints out 1. The second call executes the same code, with the same preincrement, and prints out 2.
DISCLAIMER: Not a javascript developer. Forgive me if I've made an error or used some unpreferred wording.
So the code you posted outputs 1 2. Yet the code:
function getCtr(){
var i = 0;
return function(){
console.log(++i);
}
}
getCtr()();
getCtr()();
outputs only 1 1!
The difference is that if you save a reference to getCtr() by using the var ctr = getCtr();, you create what is called a closure.
So the difference between calling getCtr()() and ctr() is that ctr has i defined in its scope, and that scope is saved thanks to var ctr = getCtr();. Because the reference is saved, the function inside of ctr is able to always act on the same variable.
run this:
var m=0;
var d=0;
alert(m++ +":"+ ++d);
and you get "0:1"
IF it were me asking in an interview, the difference in where the ++ is is what I would be after :)
http://jsfiddle.net/MarkSchultheiss/S5nJk/
Closures
The return statement in that function saves i. So when var i = 0; is only called var ctr = getCtr();. Then ctr becomes the returned function:
function () {
console.log(++i)
}
and the variable ctr has i in the scope of the outer function, getCtr() and the return function is in the scope of getCtr() as well.
okay, getCtr is a function that returns an other function.
It also contains a var called "i" which is set to 0.
"i" is also available in the scope of the returned function.
the preincrement of "i" before logging it to the console causes that it increases by 1 every time the returned function, which is stored in "ctr", is called.
When executed, function getCtr returns an inner anonymous function.
This function is now referenced by variable ctr
Because the anonymous function was created inside getCtr it will have access to getCtr private scope object, which contains variable 'i'. This is known as a closure.
var ctr = getCtr()
Every time the anonymous function is executed it pre-increments i, and writes in in the console.
ctr()
Lets break it down using terms you might know from classical inheritance based OOP languages:
// In javascript functions are first-class objects
// This function is being used like a class would be in Java
function getCtr(){
// You can think of this as a private variable of the getCtr "class"
var i = 0;
// Because it is returned, this is effectively a public method of getCtr
return function(){
// Which increments i and then prints it.
console.log(++i);
}
}
// This makes the variable ctrl an instance of getCtr.
var ctr = getCtr();
// This calls ctr's only public method.
ctr();
ctr();
So the output would be "1, 2".
What this question is meant to do is test if you understand Javascript's prototypal inheritance, ability to have anonymous functions, and closures.
A clarified version of that could that would do the same thing would be:
var myProtoype = function() {
var privateVariable = 0;
var privateMethod = function () {
privateVariable++;
console.log(privateVariable);
}
return {
publicMethod: privateMethod
};
}
var myInstance = new myPrototype();
myInstance.publicMethod();
myInstance.publicMethod();
That function is a Javascript Module. You can have a good reading about it on Javascript: the Good Parts, which is a great book and I highly recommend. A Module uses Javascript closures to create private variables and if assigned to a var the var will retain it's vars each time it's called instead of redefining the vars.
A module works like this
function moduleName(privateVar1){
var privateVar1;
var privateVar2;
return {
exposedFunction1: function (var1) {
// Do stuff... using private vars
return something;
},
exposedFunction2: function (var1, var2) {
// Do stuff...
return something;
}
}
}
var moduleInstance = moduleName(privateVar1);
moduleInstance.exposedFunction(var1);

Categories