In Secrets of Javascript Closures, Stuart Langridge presents a snippet of code to demonstrate the common usage of a closure in an .onclick callback, and paraphrasing:
link.onclick = function (e) {
var newa = document.createElement("a");
var that = this;
document.body.appendChild(newa);
newa.onclick = function (e) {
that.firstChild.nodeValue = "reset";
this.parentNode.removeChild(this);
}
}
I've recently stumbled upon Kyle Simpsons' Speaker Deck New Rules For Javascript and he mentions that saving the scope of this
for a closure like var self = this
or (like in the snippet) var that = this
is "misguided" and a case for Object.prototype.bind()
. < ES5 compatibility aside, I feel more comfortable leaning on language constructs to solve problems rather than use hacks or quick fixes, but in this code snippet, the problem for using bind
, apply
or call
is that both the reference to the enclosing value of this
and the closure's reference value of this
are needed.
Is this a case where practicality trumps philosophy? What can be done?
I wouldn't consider your example as a misguided case for bind
this and that are separate references. A misguided case for bind would be :
var that = this;
var fn = function () {
that.method();
}
return fn;
vs
var fn = function() {
this.method();
}
return fn.bind(this);
In the general case, if you really do need both this
and that
then you cannot just do away with one of the two, can you?
In the case of a click handler, you should be able to do get to the element in question by looking at the event object passed in. I believe it has a target
property of some kind. So you could use e
instead of this
and then bind to get that
as this
.
Depending on how your page is structured, you may also be able to traverse the DOM to get from this
to that
, especially if you make use of id or class to tag things semantically.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With