function() {}.bind(this) -> this.function(){} ?

# John J Barton (14 years ago)

Sorry if this has been suggested before....

I've stopped using the 'self=this' trick: ... var self = this; window.addEventListener('load', function(event) { self.foo(); }, false);

in favor of bind(): ... window.addEventListener('load', function(event) { this.foo(); }.bind(this), false);

It's fine, but I wonder if such code would be clearer if we could write: ... window.addEventListener('load', this.function(event) { this.foo(); }, false);

To me at least this more closely expresses my intent: I want an anonymous method of 'this' object, not an anonymous function.

jjb

# Rick Waldron (14 years ago)

IIRC, the block lambda proposal covers this (pun might be intended)

window.foo = function() { console.log("hi!"); };

window.addEventListener('load', {|| this.foo(); // "hi!" }, false);

strawman:block_lambda_revival#semantics

# Axel Rauschmayer (14 years ago)

Yes, block lambdas are awesome and will nearly eliminate the "dynamic this versus lexical this" quirk from JavaScript.

var obj = {
    foo: function () {
        console.log("hi!");
    },
    bar: function () {
        // block lambdas = lexical `this`
        // = picks up `this` from surrounding function
        window.addEventListener('load', {||
            this.foo(); // "hi!"
        }, false);
    }
}
# Mark S. Miller (14 years ago)

Your particular syntactic choice looks clever, but as is often the case, it fails because of semicolon insertion. The following works today on any ES5 system:

function foo() { > return this.function() > { > console.log('oops'); > }; } foo.call({function: function(){return 'gotcha';}});

gotcha