BIND, CALL and APPLY in JAVASCRIPT

Photo by Shahadat Rahman on Unsplash
Bind() method
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
function log(level, time, message) {
console.log(level + ' �" ' + time + ': ' + message);
}
function log(level, time, message) {
console.log(level + ' - ' + time + ': ' + message);
}

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

logErrToday("Server die."); // Error - Today: Server die.
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.

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.

// 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]);
function test(firstParam, secondParam, thirdParam){
var args = Array.apply(null, arguments);
console.log(args);
}

test(1, 2, 3); // [1, 2, 3]
var computer = {
accessWeb: function (site) {
// Go to some site
console.log ('Go to:' + site);
}
};

computer.accessWeb ('abc.com');
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

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Beribey

Beribey

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