rvagg / through2

Tiny wrapper around Node streams2 Transform to avoid explicit subclassing noise
MIT License
1.9k stars 106 forks source link

Arrow function leaves `this` undefined in code block. #68

Closed sgnl closed 8 years ago

sgnl commented 8 years ago

Any clarification on why this is happening?

Misc specs

Node version: 5.6.0 strict-mode: enabled via 'use strict' through2 version: 2.0.1

The Good :+1:

Works fine with keyword Function declaration:


.pipe(Through2(function(chunk, enc, callback) {
        this.push(chunk)

        callback();
}))

The Bad :-1:

_Breaks when using ES2015 Arrow Function: _

.pipe(Through2((chunk, enc, callback) => {
        this.push(chunk)

        callback();
}))

The Ugly :bug:

\ The error displayed in my cli: **

this.push(results)
            ^

TypeError: Cannot read property 'push' of undefined
  at: ...

Searched through Issues and I did not find anything related. Posting here as reference for anyone that may experience the issue in the future.

Aloha.

sgnl commented 8 years ago

Thankfully, I can still push data down the pipeline with callback(null, dataToPass).

.pipe(Through2((chunk, enc, callback) => {
    //...
    callback(null, results);
}))
brycebaril commented 8 years ago

Hi @sgnl -- I believe what you are running into is how arrow functions work: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

An arrow function expression (also known as fat arrow function) has a shorter syntax compared to function expressions and lexically binds the this value (does not bind its own this, arguments, super, or new.target).