BIND, CALL and APPLY in JAVASCRIPT

Beribey
5 min readFeb 4, 2021

These are the three functions that make up the power and dominance of JavaScript.

Photo by Shahadat Rahman on Unsplash

Bind is a function in Function.prototype so that the only function can call it. As mentioned in this article, bind is used to specify this parameter for a function.

Bind() method

As in the following case, when we pass the showName function as a callback to the button. Click function, this value here is that button. For the function to run properly, we use bind to bind the values person and this.

var person = {
firstName: 'John',
lastName: 'Wick',
showName: function() {
console.log (this.firstName + '' + this.lastName);
}
};

// showName is passed as callback, here this is the button
$('button').click(person.showName);

// Use bind to define this value
$('button').click(person.showName.bind(person));
// this is still the object person

Not only can the bind value this, but bind can also bind the parameters passed to the function. Hence, Bind can also be used to write partial functions.

A partial function creates a new function from an old function by default assigning some parameters to that old function. Please see the following specific example. I have a simple log function with 3 parameters:

function log(level, time, message) {
console.log(level + ' �" ' + time + ': ' + message);
}

Suppose I want to create another log function, record today’s error logs; I can write a new function based on the old log function:

function log(level, time, message) {
console.log(level + ' - ' + time + ': ' + message);
}

function logErrToday(message) {
log("Error", "Today", message);
}

logErrToday("Server die."); // Error - Today: Server die.

Instead of writing like that, I can write more simply by using bind. Here log is an old function, logErrToday is a new function, created by default assigning two parameters level and time.

function log (level, time, message) {
console.log (level + '-' + time + ':' + message);
}

// There is no this so this is set to null
// Set default 2 parameters level and time
var logErrToday = log.bind (null, 'Error', 'Today');

// This function corresponds to log ('Error', 'Today', 'Server die.')
logErrToday ("Server die.");
// Error - Today: Server died.

Partial Function is also called Curry (Many people say that 2 of them are one, many people say they are different). If you find the concept of partial function/curry quite strange, do not worry, they are rarely used in Java, C #, but quite commonly used in some functional programming languages such as Haskell, F #, Scala. …. . Functional programming is quite difficult to learn, has a headache, and if you want to try it, you should find the Haskell language.

Call and Apply

These two functions are on the Function prototype (Function. prototype), so only functions can call. They share the same function: Call a function, define this parameter, pass the rest of the parameters.

The difference is that apply passes to an array containing all the parameters while the call passes each parameter in turn. Easy to remember, we can reckon “A is an Array, C is many departments.”

Let’s look at this simple example of call and apply, and you will understand immediately:

// Find max by calling Math.max function
Math.max (4, 3, 2, 10);

// Instead of calling Math.max function directly, we can use call
// Set this with null
Math.max.call (null, 4, 3, 2, 10);

// Apply is similar to call, but does not pass in turn
// Which passes an array containing all the parameters
Math.max.apply (null, [4, 3, 2, 10]);

Call and apply are often used to borrow functions. Do you try to read the following code to do?

function test(firstParam, secondParam, thirdParam){
var args = Array.apply(null, arguments);
console.log(args);
}

test(1, 2, 3); // [1, 2, 3]

Hint: Arguments is a local variable in the function, containing all the parameters passed.

Answer: An argument is an object like an array but not an array. Arguments are like arrays because it has field length, can access the values it contains via index 0,1,2. However, since arguments are not an array, it cannot call the Array.prototype functions.

Therefore, we have to use call / apply to borrow some functions in Array.prototype, which will return an array for us to process. The above line of code converts the arguments object into an array. Why so troublesome ?? Why is no argument that an array always goes for simple things? When I first knew this argument, I also wanted to swear like that.

Alternatively, call and can be used for monkey-patching or creating spy. It is possible to extend the functionality of a function without modifying its source code. For example, we have the accessWeb function of the object computer.

var computer = {
accessWeb: function (site) {
// Go to some site
console.log ('Go to:' + site);
}
};

computer.accessWeb ('abc.com');

Using call, we can add logs before and after the accessWeb function is called without interfering with the function’s code.

var computer = {
accessWeb: function (site) {
// Go to some site
console.log ('Go to:' + site);
}
};

var oldFunction = computer.accessWeb;
// Replace the function accessWeb with the new function
computer.accessWeb = function () {
console.log ('start to web');
oldFunction.apply (this, arguments); // keep the old function
console.log ('entered web');
}

computer.accessWeb ('abc.com');

References

--

--

Beribey

Always be nice to anybody who has access to my toothbrush.