Top community members
All Wiki Articles Create Wiki Article

Welcome to Dirask IT community! ❤ 💻
We are community that shares solutions with each other.

If you think you have something to add here.

you are welcome with your fresh ideas - List Articles

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

0 contributions
1 points

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.

0 contributions

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more