@jgCarroll/

bindMethod

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
28
29
30
31
32
33
// this.distance = 10000 // defined on the global scope, therefore taking precedence

// const roadTrip1 = {
//   distance: 3000,
//   getDistance: function() {
//     return this.distance
//   }
// }

// const getTripDistance = roadTrip1.getDistance

// getTripDistance() // as the code is, the distance of 10000 is logged out

// ==================================
// the same code, but using the bind() method
this.distance = 10000 

const roadTrip1 = {
  distance: 3000,
  getDistance: function(unit, caption) {
    return this.distance + unit + caption
  }
}

const roadTrip2 = {
  distance: 5000
}

// const getTripDistance = roadTrip1.getDistance.bind(roadTrip1)

const getTripDistance = roadTrip1.getDistance.bind(roadTrip2, 'km') // added a unit parameter to the bind method

getTripDistance(' in total') // now, because of the bind() method, it logs out 3000 or 5000. Notice that unit and caption are added as parameters to roadTrip1
Native Browser JavaScript