@jgCarroll/

callAndApplyMethods

JavaScript

A common interview question

fork
loading
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// call() method

const car1 = {
  brand: 'Porsche',
  getCarDescription: function(cost, year, color) {
    console.log(`This car is a ${this.brand}. The price is $${cost}. The year is ${year}. The color is ${color}. \n`)
  }
}

// Common way of calling this code
car1.getCarDescription(80000, 2010, 'blue')

// if I create a second object, I can then use the call() method to access parts of the first object
const car2 = {
  brand: 'Lamborghini'
}

car1.getCarDescription.call(car2, 200000, 2017, 'green')

// ==============================
// apply() method

const car3 = {
  brand: 'Ford'
}

car1.getCarDescription.apply(car3, [35000, 2016, 'black'])
Native Browser JavaScript