My goal is to use closures while still writing clean code. One thing I noticed is that somehow I always end up repeating myself because one of my anonymous functions is needed in more than one case.
To this goal, I want to have these repeated functions stored in an object which I can later reuse.
Now, to my question. I've created this example http://jsfiddle.net/tiagoespinha/tTx64/ and the alert will not fire, because y is null.
However, if I inline the function, everything works fine http://jsfiddle.net/tiagoespinha/tTx64/1/
Is there a trick to work around this? How can I have it working in the first example? The variable y is still there, why can't JS catch it?
You want objects having own variables (y) and sharing functions.
What you really need is probably prototype.
function Holder() {
this.y = 5;
this.myFn();
}
Holder.prototype.myFn = function() {
alert("The value of the closure var is " + this.y);
}
new Holder();
I'd suggest the reading of Introduction to Object-Oriented JavaScript so that you don't try to rebuild OOP with just closures.
//our constructor, each instance will carry a y of 5
function Proto() {
this.y = 5;
}
//a shared function for all instances
Proto.prototype.returnedFn = function() {
alert("The value of the closure var is " + this.y);
}
//just a wrapper for the new instance call.
//I just like it this way to avoid using "new" when making instances
function newFn() {
//return a new instance
return new Proto();
}
//test it out
newFn().returnedFn();
newFn().returnedFn();
Your first example would need some kind of dynamic scoping to work. Javascript is statically scoped.
Closures allow a function to capture some local variables from the scope it's defined in. Holder.myFn isn't defined in a scope that contains variable y.
Also note that every instance of a function has its own closure. Hence it's not possible to define your function once and have it refer to different y's in different contexts. (In your second example the inner function is defined every time you call newFn, so many instances can exist, each with its own copy of y.)
I will also add an answer to my own question to report my findings.
Based on the other solutions provided and partly using the OOP solution, I found another way which also makes use of closures.
// Object prototype which takes an argument
function MyObj(abc) {
// Declare function using a closure
// and thus being able to use the argument
this.myFn = (function(){
return function() {
alert("abc is " + abc);
};
})();
}
// Then we can simply create an object with the
// desired argument and the function will behave as expected
var v = new MyObj(10);
v.myFn();
I think nobody provided this solution possibly because I omitted that I don't really want to store the values locally in the object. I simply want to pass some values in, make use of them in one function and then get rid of the object.
In this case I believe a pure OOP solution might be overkill.
Anyhow, thank you for all the proposed solutions!
Related
Let me ask one question. It's about closures in JavaScript, but not about how they work.
David Flanagan in his "JavaScript The Definitive Guide 6th Edition" wrote:
...Technically, all JavaScript functions are closures: they are objects, and they have a scope chain associated with them....
Is this correct? Can I call every function (function object + it's scope) a "closure"?
And stacks' tag "closures" says:
A closure is a first-class function that refers to (closes over) variables from the scope in which it was defined. If the closure still exists after its defining scope ends, the variables it closes over will continue to exist as well.
In JavaScript every function refers to variables from the scope in which it was defined. So, It's still valid.
The question is: why do so many developers think otherwise? Is there something wrong with this theory? Can't it be used as general definition?
Technically, all functions are closures. But if the function doesn't reference any free variables, the environment of the closure is empty. The distinction between function and closure is only interesting if there are closed variables that need to be saved along with the function code. So it's common to refer to functions that don't access any free variables as functions, and those that do as closures, so that you know about this distinction.
It's a tricky term to pin down. A function that's simply declared is just a function. What makes a closure is calling the function. By calling a function, space is allocated for the parameters passed and for local variables declared.
If a function simply returns some value, and that value is just something simple (like, nothing at all, or just a number or a string), then the closure goes away and there's really nothing interesting about it. However, if some references to parameters or local variables (which, mostly, are the same) "escape" the function, then the closure — that space allocated for local variables, along with the chain of parent spaces — sticks around.
Here's a way that some references could "escape" from a function:
function escape(x, y) {
return {
x: x,
y: y,
sum: function() { return x + y; }
};
}
var foo = escape(10, 20);
alert(foo.sum()); // 30
That object returned from the function and saved in "foo" will maintain references to those two parameters. Here's a more interesting example:
function counter(start, increment) {
var current = start;
return function() {
var returnValue = current;
current += increment;
return returnValue;
};
}
var evenNumbers = counter(0, 2);
alert(evenNumbers()); // 0
alert(evenNumbers()); // 2
alert(evenNumbers()); // 4
In that one, the returned value is itself a function. That function involves code that makes reference to the parameter "increment" and a local variable, "current".
I would take some issue with conflating the concept of a closure and the concept of functions being first-class objects. Those two things really are separate, though they're synergistic.
As a caveat, I'm not a formalist by basic personality and I'm really awful with terminology so this should probably be showered with downvotes.
I would try to answer your question knowing you were asked about what closures are during the interview (read it from the comments above).
First, I think you should be more specific with "think otherwise". How exactly?
Probably we can say something about this noop function's closure:
function() {}
But it seems it has no sense since there are no variables would bound on it's scope.
I think even this example is also not very good to consider:
function closureDemo() {
var localVar = true;
}
closureDemo();
Since its variable would be freed as there is no possibility to access it after this function call, so there is no difference between JavaScript and let's say C language.
Once again, since you said you have asked about what closures are on the interview, I suppose it would be much better to show the example where you can access some local variables via an external function you get after closureDemo() call, first. Like
function closureDemo() {
var localVar = true;
window.externalFunc = function() {
localVar = !localVar; // this local variable is still alive
console.log(localVar); // despite function has been already run,
// that is it was closed over the scope
}
}
closureDemo();
externalFunc();
externalFunc();
Then to comment about other cases and then derive the most common definition as it more likely to get the interviewer to agree with you rather than to quote Flanagan and instantly try to find the page where you've read it as a better proof of your statement or something.
Probably your interviewer just thought you don't actually know about what closures are and just read the definition from the book. Anyhow I wish you good luck next time.
The definition is correct.
The closure keeps the scope where it was born
Consider this simple code:
getLabelPrinter = function( label) {
var labelPrinter = function( value) {
document.write(label+": "+value);
}
return labelPrinter; // this returns a function
}
priceLabelPrinter = getLabelPrinter('The price is');
quantityLabelPrinter = getLabelPrinter('The quantity is');
priceLabelPrinter(100);
quantityLabelPrinter(200);
//output:
//The price is: 100 The quantity is: 200
https://jsfiddle.net/twqgeyuq/
I know this subject had been dealt a lot here, but I saw this specific example on the Pluralsight JS design pattern course, and I'll be glad for your help understanding the closure there.
This is the example:
var Calc = function(start) {
var that = this;
this.add = function(x) {
start = start + x;
return that;
};
this.multiply = function(x) {
start = start * x;
return that;
};
this.equals = function(callback) {
callback(start);
return that;
};
}
new Calc(0)
.add(1)
.add(2)
.multiply(3)
.equals(function(result){
console.log(result); // returns 9
});
Here's the JSFiddle link: http://jsfiddle.net/3yJ8Y/5/
I'll be VERY glad for:
Understanding the "that" use. Why do we need it in this specific
example? it does the same with "this". Can you pls give examples and explain when do we need to do "var that = this"?
Understanding this way of creating functions from an object. why do we have to use "this" and then .functionName? like this.add = ...
A detailed and extensive explanation for this very specific closure example.
Thank you so much!
start becomes a global variable of the Calc object
Each method of the Calc object (add, multiple, equals) references that same global variable
new Calc(0) // <- sets start to 0
.add(1) // calls add() <- sets start to 1
.add(2) // calls add() <- sets start to 3
.multiply(3) // calls multiple() <- sets start to 9
.equals(function(result){
console.log(result); // returns 9
});
Thanks to #elclanrs for reminding me of things I had internalized and forgotten...
That
The important thing here is that that... is unnecessary.
I'll quote an article that #elclanrs linked in his comment on the above post:
Scope In Javascript
JavaScript establishes an execution context for the function call, setting this to the object referenced by whatever came before the last ”.”
Because each method is called with the outer Calc before it's dot, the this value inside that method is assigned as the outer object.
The outer object, in turn, is its own brand new, self-contained scope because it was created with the new keyword:
When new[Calc]() is executed, a completely new object is created transparently in the background. [Calc] is called, and its this keyword is set to reference that new object.
(Scope in Javascript, again, with my edits in brackets).
Now you might be wondering, "How is this:
.add(1)
.add(2)
.multiply(3)
... keeping the right scope? You said that whatever is before the . is passed in as the this variable in this situation!?"
Absolutely true, and in this situation, each method is returning this, which allows method chaining. (They're actually returning that, but we already determined that was an unnecessary variable in this context).
Why use that
First of all, let me say I prefer var self = this over var that = this but there are arguments either way.
Let's arbitrarily modify the object to have a method that looks like this:
this.getInternalThis = function(){
var internalThis = function(){
console.log( this );
}
}
First of all, let's get this out of the way: this example is stupid, but you'll see things like this - a function defined in other scopes - all the time.
Here are the important things to notice:
It's called by name, and nothing more (no prefixed . notation, for example)
... that's it!
When a function is called this way, the engine has to figure out something to assign this as in the scope of the function. It defaults to window.
If you were to run this code, you would get Window in the console.
Now, what if we wanted this inside that internal function call to be the calling value of this?
This situation is where you need a that variable. We can modify the function to look like:
this.getInternalThis = function(){
var that = this,
internalThis = function(){
console.log( that );
};
}
Now when you run this method, you get the value of the calling object in the console.
In my case it was Object { add=function(), multiply=function(), equals=function(), getInternalThis=function()}.
Sometimes, that's what you need or expect, so that's why you would use a var that = this declaration.
Using this. to define a method
As I mentioned earlier:
Because each method is called with the outer Calc before it's dot, the this value inside that method is assigned as the outer object.
Remember that this in the scope of Calc() is a reference to the new Calc object, so each method is being given the Calc object as the value of this (remember, it's before the .!) when they enter their new scope from that context.
Hopefully this gives you a little info on how JavaScript scopes and the assignment of this works.
In Introduction to Object-Oriented JavaScript, a formal description is given on how to use javascript in an object oriented fashion. Your code for functions inside objects would like along the lines of:
$(function() {
var oPerson = new cPerson("Florian");
alert("Hi! My name is " + oPerson.sMyNameIs());
});
function cPerson(sSetName)
{
var sName= sSetName;
var oPersonInst = this;
this.sMyNameIs = function () {
return sName;
};
}
With a bit more experience, you probably want a more clearcut reference to the instantiated class, so you modify the class code as such (and I add another function too):
function cPerson(sSetName)
{
var sName= sSetName;
var oPersonInst = this;
this.sMyNameIs = function () {
return oPersonInst.sName;
};
this.sMyFullNameIs = function () {
return oPersonInst.sMyNameIs();
};
}
Now we have come accross three different ways of referring to function or variables from within class functions:
return sName;
return this.sName;
return oPersonInst.sName;
Suppose I want to call the sName variable in the instantiated class very specifically, and these example functions will get more and more and even more complex and in depth as development goes on.
I think that the first option ('return sName;') is uncertain, as you are not quite sure whether you are referring to the variable in the right targeted instantiated class scope. It could be an accidental local var that you are calling.
The second, using this, IMHO, is also not perfect as this apparently changes depending on situations, and you can't (?) rely on that you are calling the right variable in the instantiated class specifically.
So the third reference, is IMHO, the best looking reference. Very specifically defined right at instantiation of the class. How can there be any doubt that the var sName of the class is meant.
Q1: Why are functions in the class defined with this.? Can it not better be defined with oPersonInst.something = function () { //... }; ?
Q2: why does, in code that I have given, alert(oPersonInst.sMyNameIs()); work, but alert(oPersonInst.sName); does not (at least, not within $.each( something, function() { //right here }) ), but alert(sName); DOES work (not favored IMHO, because of the above mentioned reasons)?
Q3: Can someone pot some exemplary code, or maybe even change this sample code, where solid out-of-local-scope references are used, that will work outside as well as inside $.each(...) callback functions (or other callback related functions) ?
Forgive my confusion, we're all learners, and I feel a hole in my brain. This article did not explain my concerns over this very well.
this doesn't change randomly at all.. it always means the current closure (function):
if you are in function_1() -- this means function_1
if you are in function_1>function_2 -- function_2 is the current closure and this means function_2
IF you need function_1's this in function_2 you have to capture it while in function_1: meaning var function1This = this;
and the way to reference a var by using the functions name before it means static access. It has different semantics
so use this.var to be sure you get the INSTANCE's variable
use a 'captured this pointer' to access your parents INSTANCE's variable
and only use name.var if you want to get the static, shared (between all instances) value
I click a button and there is a handler. I have never understood if I should use a closure, or let the handler be in a object. For example, in HTML I have,
<button id="b">Go</button>
<button id="c">Go</button>
and in JavaScript (with some jQuery),
var hdl=function(){
var hdl=function(){
foo+="foo"
console.log(foo)
},
foo=""
return hdl
}()
$("#b").click(hdl)
var obj={
bar:"",
hdl:function(){
this.bar+="bar"
console.log(this.bar)
}
}
var baz=function(){
obj.hdl()
}
$("#c").click(baz)
Both work. Or are there situations in which you can only use one of them?
An event handler is always a function or an object that implements the EventListener interface. I've never understood any reason to use an EventListener object rather than a function so I've only seen functions used, but you can use either.
If you choose a function, it's up to you whether you want a function to be a global function, an anonymously declared function or a function that is a property of an object. There is no "right" answer as it depends upon how you want to structure your code.
My event handlers are usually anonymously declared functions just because that's usually how I structure things and generally nothing more is needed. Simple is best so you should make it no more complicated than needed.
A closure is just a function body that survives longer than the simple execution of the function because some other function reference inside is still active. Whether to use a closure or not depends on your needs and again the structure of your code. Closures can be really handy ways of keeping some state without using global variables, but other times they aren't needed at all.
I think you're mixing up terms.
Closures are a natural result of JavaScript's scoping rules, not something you choose to create
The jQuery click event always takes a function. Whether that function is attached to an object—thereby making it a method—doesn't really matter. Depending on how that function is written, it may form a closure that affects you.
A closure is when a function "remembers" the variables in the context in which it's defined.
The classical closure example is something like this:
for(var i = 0; i < 10; i++)
$("#button" + i).click(function() { alert("you clicked button " + i); });
Most developers are surprised to learn that each button displays 10, which is the value of i when the outer scope ends. This happens because each of those functions declared in the loop has formed a closure over i. Those functions don't just get the value of i when they're declared, they get the actual i, in all its glory. That's why changing i after you create the function causes the created function to reflect the updated value of i
Situations like this are fixed by breaking the closure by passing i to a function, since function parameters are passed by value.
for(var i = 0; i < 10; i++)
(function(localI) {
$("#button" + i).click(function() { alert("you clicked button " + localI); });
)(i);
The only difference between your cases is that in one of them you are bundling your variables (foo) in an object. The following third example should make this point clear:
function hdl(variables){
variables.foo += variables.foo;
}
var obj = {foo: ""};
var baz = function(){
hdl(obj);
}
I don't think any of these alternatives is in anyway generally superior to the others. You should decide to use whatever solution is simpler and easier to understand and mantain depending on what your particular problem is.
For example, in the version using objects the variables are dinamically bound while in the version with closures they are statically bound. This means that the object version is more extensible (with inheritance, mixins, etc) while the closure version is more rigid (but simpler to reason about at compile time)
I am not great with anything beyond basic javascript so please forgive the simple question.
I am using the jsDraw2D library. This library has a graphics object that looks something like the following:
function jsGraphics(canvasDivElement) {
var canvasDiv;
this.drawLine = drawLine;
function drawLine(point1, point2) {
// do things with canvasDiv
}
}
You use it like this:
var gr = new jsGraphics(document.getElementById('canvas'))
gr.drawLine(new jsPoint(0,0), new jsPoint(10,10))
I would like to add a function to jsGraphics so that I can call
gr.getCanvasElement()
Is there a way to do this without editing the library itself?
I have tried
jsGraphics.prototype.getCanvasElement = function() { return canvasDiv }
but this doesn't seem to work. I have an intuitive feeling that its something with that new keyword but if you could explain why exactly it doesn't that would be helpful too.
Nope, this isn't using the normal JavaScript prototype-based inheritance, it's adding a separate drawLine function to every instance of jsGraphics, each with a closure around its own canvasDiv variable.
Once function jsGraphics() { is closed } there is no further way to access the canvasDiv variable at all, unless one of the functions inside provides access to it. This is often done deliberately to make private variables, explicitly to stop you getting at canvasDiv.
You can't just get to the canvasDiv element necessarily, because if it is never assigned to the object in the constructor using the this keyword, the reference to that object exists in a closure created by the constructor function itself.
You can however wrap the constructor in a new constructor and then set the prototypes equal:
function myJsGraphics(canvasDivElement) {
this.canvasDiv = canvasDivElement;
jsGraphics.call(this, cavasDivElement);
}
myJsGraphics.prototype = jsGraphics.prototype;
Now you should be able to access the element using your new constructor:
var obj = new myJsGraphics(document.getElementById('blah-elem'));
elem = obj.canvasDiv;
The whole closure thing is a little weird if you're not used to it, but the gist is that functions defined in a certain scope but available elsewhere can refer to variables in the scope in which they were defined at all times. The easiest example is when you have a function that returns a function:
function makeIncrementer(start) {
return function () { return start++; };
}
var inc = makeIncrementer(0);
var inc2 = makeIncrementer(0);
inc(); // => 0
inc(); // => 1
inc(); // => 2
inc2(); // => 0
That reference to the "start" variable is "closed over" when the function is returned from the makeIncrementer function. It cannot be accessed directly. The same thing happens in an object's constructor, where local variables are "closed" into the member functions of the object, and they act as private variables. Unless there was a method or variable reference to a private member defined in the constructor, you just can't get access to it.
This "private state" technique has become more and more idiomatic in the last few years. Personally I've found it oddly limiting when trying to quickly debug something from the console or override behavior in a 3rd party library. It's one of the few times I think "Damn it, why can't I do this with the language". I've exploited this bug in Firefox 2 to good effect when I've really needed to debug a "private variable" quickly.
I'd be curious to know when others use this idiom or when they avoid it. (#bobince I'm looking at you).
Anyway #bobince has pretty much answered your question (nutshell: No, you can't access the canvasDiv variable from the scope you are in).
However, there is one thing you can do that is a tradeoff between a hack or editing the 3rd-party library (I always go for the hack ;): you can augment the object to hold a reference you know you will need later.
Hack 1: if you control the object instantiations yourself:
var canvas = document.getElementById('canvas');
var gr = new jsGraphics(canvas);
gr._canvasDiv = canvas; // Augment because we'll need this later
// Sometime later...
gr._canvasDiv; // do something with the element
If the library supports some concept akin to a destructor (fired on unload of the page or something), be sure to null out or delete your property there too, to avoid memory leaks in IE:
delete gr._canvasDiv;
OR Hack 2: Overwrite the constructor just after including the library:
// run after including the library, and before
// any code that instantiates jsGraphics objects
jsGraphics = (function(fn) {
return function(canvas) {
this._canvasDiv = canvas;
return fn.apply(this, arguments)
}
}(jsGraphics))
Then access the element (now public) as gr._canvasDiv. Same note about deleting it on page unload applies.