1 year ago

#72693

test-img

djoo

Difference in function declaration within objects JavaScript

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?

javascript

function

syntax

javascript-objects

function-declaration

0 Answers

Your Answer

Accepted video resources