Call() and apply() in JavaScript

Understand how to use call() and apply() and their differences in JavaScript

call() and apply() are two functions provided by JavaScript to perform very specific tasks: call a function and set itthisvalue.

Look at mine"This" guideLearn all the details about this specific variable

A function can be usedthisThe value of many different use cases. The problem is that it is provided by the environment and cannot be changed from the outside unless it is usedcall()orapply().

When using these methods, you can pass in an additional object, which will be used asthisIn the called function.

These functions perform the same operations but are different. incall()You can pass function parameters as a comma-separated list of parameters and enter as many parameters as needed.apply()You pass a single array containing parameters:

const car = {
  brand: 'Ford',
  model: 'Fiesta'
}

const drive = function(from, to, kms) { console.log(Driving for </span><span style="color:#e6db74">${</span><span style="color:#a6e22e">kms</span><span style="color:#e6db74">}</span><span style="color:#e6db74"> kilometers from </span><span style="color:#e6db74">${</span><span style="color:#a6e22e">from</span><span style="color:#e6db74">}</span><span style="color:#e6db74"> to </span><span style="color:#e6db74">${</span><span style="color:#a6e22e">to</span><span style="color:#e6db74">}</span><span style="color:#e6db74"> with my car, a </span><span style="color:#e6db74">${</span><span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">brand</span><span style="color:#e6db74">}</span><span style="color:#e6db74"> </span><span style="color:#e6db74">${</span><span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">model</span><span style="color:#e6db74">}</span><span style="color:#e6db74">) }

drive.call(car, ‘Milan’, ‘Rome’, 568) drive.apply(car, [‘Milan’, ‘Rome’, 568])

Please note that when usingArrow function thisNo restrictions, so this method is only suitable for regular functions.

Download mine for freeJavaScript beginner's manual


More js tutorials: