gremo
gremo

Reputation: 48899

Why the execution context ("this") of prototypical function is wrong in this example?

Prototypical function bar is executed elsewhere, in a Node.js environment (where bind should be available). I want this inside bar() function to be the instance of my object:

var Foo = function (arg) {
    this.arg = arg;

    Foo.prototype.bar.bind(this);
};

Foo.prototype.bar = function () {
    console.log(this); // Not my object!
    console.log(this.arg); // ... thus this is undefined
}

var foo = new Foo();
module.execute('action', foo.bar); // foo.bar is the callback 

... why bar() logs undefined and this is not my instance? Why the execution context was not changed by the bind call?

Upvotes: 2

Views: 110

Answers (1)

Matt Ball
Matt Ball

Reputation: 359786

Function.bind returns a value - the newly bound function - but you just discard that value. Function.bind does not alter this (that is, its invocation context), nor does it alter its arguments (this).

Is there another way to get the same result?

Doing it inside of the constructor function is actually wrong, because bar lives on Foo.prototype, so binding it to any one instance of Foo would break this for all other Foo.bar calls! Bind it where you mean it:

module.execute('action', foo.bar.bind(foo));

Or – maybe even simpler – don't define bar on the prototype at all:

var Foo = function (arg) {
    this.arg = arg;

    function bar () {
        console.log(this);
        console.log(this.arg);
    }

    this.bar = bar.bind(this);
};

var foo = new Foo();
module.execute('action', foo.bar);

Upvotes: 6

Related Questions