3

Trying to figure out how to do an arrow function while maintaining this.emit(). In gulp and ES6 I have a function like so:

gulp.src([paths.sass])
    .pipe(sourcemaps.init())
    .pipe(sass().on('error', function (e) {
      reportError(e);
      this.emit('end');
    }))

Notice the usage of this.emit('end'). Works great when I use a non arrow function, but the second I do:

gulp.src([paths.sass])
    .pipe(sourcemaps.init())
    .pipe(sass().on('error', (e) => {
      reportError(e);
      this.emit('end');
    }))

this.emit('end') is no longer available. How could I write that function using an arrow function and maintain the this.emit()

allencoded
  • 7,015
  • 17
  • 72
  • 126

2 Answers2

1

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

in arrow function of ECMAScript2015, this always referencing outside function, no runtime context.

meaing:

function out() {
  var name = "out"
  return function() {
    return function() {
      return function() {
        console.log(this.name)   // out
      }
    }
  }
}
  • arrow function no Object arguments
  • arrow function can't using yield
  • arrow function can't initialized by new
Muge
  • 469
  • 5
  • 11
0

If the on method of the sass() returned object arranges to call the supplied function as a method of another object, and the function needs to pick up the value of the object it is called on, in order to call its emit method, use the function declaration.

Arrow functions avoid using Function.prototype.bind on the current this value of the defining context, by always using the defining context's this value inside the function. Another aspect of arrow functions is that they can't be used as constructors. Arrow functions do not deprecate function declarations and expressions and should only be considered "preferable" on a case by case basis.

traktor
  • 17,588
  • 4
  • 32
  • 53