0

What's the difference in declaring functions like this in JavaScript

const sub = {
  _unsubscribed: false,
  unsubscribe() {
    this._unsubscribed = true
  },
  next(value) {
    if (this._unsubscribed) return;
    if (subscriber instanceof Function) return subscriber(value);
    return subscriber.next ? subscriber.next(value) : null;
  },
  error(error) {
    if (this._unsubscribed) return;
    this._unsubscribed = true;
    return subscriber.error ? subscriber.error(error) : null;
  },
  complete() {
    if (this._unsubscribed) return;
    this._unsubscribed = true;
    return subscriber.complete ? subscriber.complete() : null;
  }
}

versus this:

const sub = {
  _unsubscribed: false,
  unsubscribe: () => this._unsubscribed = true,
  next: (value) => {
    if (this._unsubscribed) return;
    if (subscriber instanceof Function) return subscriber(value);
    return subscriber.next ? subscriber.next(value) : null;
  },
  error: (error) => {
    if (this._unsubscribed) return;
    this._unsubscribed = true;
    return subscriber.error ? subscriber.error(error) : null;
  },
  complete: () => {
    if (this._unsubscribed) return;
    this._unsubscribed = true;
    return subscriber.complete ? subscriber.complete() : null;
  }
}

When using the object instance sub to call the functions within itself repeatedly, what are the properties of using the first method versus the second method?

djoo
  • 1
  • I'm pretty sure `error(error) {` is an ecma2015 shorthand for `error: function error(error) {`. So the difference is that one is an arrow function, the other isn't. Also bear in mind that using `this` inside an arrow function will likely return the global object. – evolutionxbox Jan 20 '22 at 01:14
  • [Arrow function expressions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions). – tao Jan 20 '22 at 01:15
  • @evolutionxbox close but [not quite](https://stackoverflow.com/a/44117363/1048572). But yes, unlike the arrow functions they have normal dynamic `this` – Bergi Jan 20 '22 at 01:48

0 Answers0