Languages
[Edit]
EN

JavaScript - what is the difference between call, apply and bind (call vs apply vs bind)?

1 points
Created by:
JustMike
3515

In JavaScript it is possible to change context of executed method. It mans we can change this keyword reference during executing some function (method). In this article brief comparision of each method has been presented.

1. Methods diffence

Method name description
myFunction.call(context, ...) calls method with new context; after context arguments passed to myFunction should be placed
myFunction.apply(context, argsArray) calls method with new context; after context array of arguments of myFunction should be placed
myFunction.bind(context) creates proxy function with new context and returns reference to it

2. Methods comparision example

function print(a, b, c) {
    var text = 'context-name: ' + this.name + ', '
        +'argument-values: [a=' + a + ', b=' + b + ', c=' + c + ']';

    console.log(text);
}

var Manager = {
    name: 'MANAGER'
};


print(1, 2, 3);

print.call(Manager, 1, 2, 3);
print.apply(Manager, [1, 2, 3]);

var printProxy = print.bind(Manager);
    
printProxy(1, 2, 3);

Output:

context-name: undefined, argument-values: [a=1, b=2, c=3]
context-name: MANAGER, argument-values: [a=1, b=2, c=3]
context-name: MANAGER, argument-values: [a=1, b=2, c=3]
context-name: MANAGER, argument-values: [a=1, b=2, c=3]

Note: methods comparison with object methods as source code examples has been presented here.

Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.