default this binding for ES-next strict mode.
Axel Rauschmayer
axel at rauschma.de
Fri Nov 18 13:40:39 PST 2011
One more comment: fixing the `this` problem is why I like lambda blocks so much: They can only be used in a non-method capacity and the meaning of `this` does not have to change, dynamically, any more – it is always lexically bound.
On Nov 18, 2011, at 22:18 , Jake Verbaten wrote:
> 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).
> _______________________________________________
> es-discuss mailing list
> es-discuss at mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss
--
Dr. Axel Rauschmayer
axel at rauschma.de
home: rauschma.de
twitter: twitter.com/rauschma
blog: 2ality.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20111118/54a255fb/attachment-0001.html>
More information about the es-discuss
mailing list