default this binding for ES-next strict mode.
Jake Verbaten
raynos2 at gmail.com
Fri Nov 18 13:18:29 PST 2011
Currently in ES5 strict mode the value of `this` is `undefined` by default.
function foo() {
return this;
}
foo(); // undefined
function foo() {
return (function () {
return this;
}());
}
foo.call(o); // undefined
Since the default value of `this` is always undefined, the `var that =
this;` or `var self = this;` pattern has occurred. An alternative to this
pattern is using .bind on a function.
var Obj = {
method: function () {
var that = this;
el.addEventListener("click", function () {
that.doSomethingElse();
});
}
}
Basically whenever a javascript developer want's to do an asynchronous
operation using a closure inside a method he has to keep a handle on the
value of `this` because the value of `this` inside the closure is useless.
This is more common in environments where asynchronous operations are more
common, like node.js.
What if we changed the value of `this` inside local function declarations
to be the value of this in the outer function. That would mean
function foo() {
return (function () {
return this;
}());
}
foo.call(o); // o
Pros:
- Removes the majority of the use-cases for `var that = this`
- Puts a value of `this` to good use rather then being `undefined`.
Cons:
- Makes `this` more "confusing"
- Breaks ES5 strict code that assumes `this === undefined`
Personally I say that value of `this` is undefined in ES5 strict. So nobody
uses it. So this is an optional addition that would make life easier for
people who want to use it.
Optional: Change the value of `this` to be the outer function `this` in
non-strict mode (breaking a large amount of code. I don't think we can get
away with that).
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20111118/9e2db914/attachment.html>
More information about the es-discuss
mailing list