nlivaic
10/31/2018 - 9:12 PM

.call() and .apply()

.call() and .apply()

let o = {
  carId: 123,
  getId: function() {
    return this.carId;
  },
  getIdWithPrefix: function(prefix) {
    return prefix + this.carId;
  }
};

let newCar = { carId: 456 };

console.log(o.getId());                                          // 123
console.log(o.getId.call(newCar));                               // 456
console.log(o.getId());                                          // 123
console.log(o.getIdWithPrefix.apply(newCar, ['somePrefix']));    // somePrefix456