You-dont-know-js: "this & object prototypes": ch2, Could it possible to avoid using self and arrow-function here?

Created on 27 Apr 2016  路  2Comments  路  Source: getify/You-Dont-Know-JS

In ch2 this part: Lexical this

It said at last:

Embrace this-style mechanisms completely, including using bind(..) where necessary, and try to avoid self = this and arrow-function "lexical this" tricks.

Could it possible to avoid using self=this and arrow-function in the example which is illustrated?

function foo() {
    setTimeout(() => {
        // `this` here is lexically adopted from `foo()`
        console.log( this.a );
    },100);
}

var obj = {
    a: 2
};

foo.call( obj ); // 2

Most helpful comment

Could it possible to avoid using self=this and arrow-function

Yes:

function foo() {
    setTimeout(function() {
        console.log( this.a );
    }.bind(this),100);
}

var obj = {
    a: 2
};

foo.call( obj ); // 2

All 2 comments

Could it possible to avoid using self=this and arrow-function

Yes:

function foo() {
    setTimeout(function() {
        console.log( this.a );
    }.bind(this),100);
}

var obj = {
    a: 2
};

foo.call( obj ); // 2

@getify beautiful:heart:

Was this page helpful?
0 / 5 - 0 ratings