Languages
[Edit]
EN

JavaScript - difference between call, apply and bind

1 points
Created by:
Palpys
764

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

1. Methods difference

Method namedescription
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 a proxy function with a new context and returns a reference to it

2. Methods comparison

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.

Alternative titles

  1. JavaScript - call vs apply vs bind
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join