Ad

JS Through2 Arrow Function This.push()

I have a problem with lexical binding in JavaScript. This is my code:

.pipe(through.obj((url, enc, done)=>{
        if(!url) return done();
        request.head(url, (err, response)=>{
            this.push(url + ' is ' + (err ? 'down' : 'up') + '\n');
            done();
        });
    }))

I get this error:

TypeError: this.push is not a function

But when I use es5 function syntax like function(url,enc,done){...}:

.pipe(through.obj(function(url, enc, done){
        if(!url) return done();
        request.head(url, (err, response)=>{
            this.push(url + ' is ' + (err ? 'down' : 'up') + '\n');
            done();
        });
    }))

then my code works well.

In this case, how can I use this.push() with the Arrow Function? I know about Arrow Function's lexical binding, but I have no idea about using this.

Thanks for reading my text.

Ad

Answer

Well in the former case, your this is pointing to window object. That's why you're getting the error.

arrow functions don't provide their own this binding (they retain the this value of the enclosing lexical context)

In arrow functions, this retains the value of the enclosing lexical context's this. In global code, it will be set to the global object:

var globalObject = this; var foo = (() => this); console.log(foo() === globalObject); // true

Check this out MDN-this particularly Arrow functions Section

Ad
source: stackoverflow.com
Ad