JS call, apply, bind



В JavaScript функции имеют свои методы такие как apply(), call() и bind().



Их суть - заставить функцию использовать контекст объекта.

 function promote(position, salary) {

this.salary = salary

this.position = position

return this.position + ' earns ' + this.salary + ' dollars'

}



Метод call() позволяет нам легко выставлять какой именно объект будет this в момент вызова функции.

 const junior = {

name: 'Fritz',

position: 'junior developer',

salary: 1000

}



const res = promote.call(junior, 'super junior developer', 1200)

Результатом будет:

super junior developer earns 1200 dollars



Методы apply и call отличаются тем, что метод apply принимает аргументы в виде массива, а не списка.

 const res = promote.apply(junior, [ 'super junior developer', 1200 ])



Метод bind позволяет выполнить отложенный вызов функции.

Сначала передаем контекст выполнения:

 const bounded = promote.bind(junior)



Потом вызываем:

 const res = bounded('super junior developer', 1200)