Hard binding vs call [duplicate] - javascript

I already know that apply and call are similar functions which set this (context of a function).
The difference is with the way we send the arguments (manual vs array)
Question:
But when should I use the bind() method ?
var obj = {
x: 81,
getX: function() {
return this.x;
}
};
alert(obj.getX.bind(obj)());
alert(obj.getX.call(obj));
alert(obj.getX.apply(obj));
jsbin

Use .bind() when you want that function to later be called with a certain context, useful in events. Use .call() or .apply() when you want to invoke the function immediately, and modify the context.
Call/apply call the function immediately, whereas bind returns a function that, when later executed, will have the correct context set for calling the original function. This way you can maintain context in async callbacks and events.
I do this a lot:
function MyObject(element) {
this.elm = element;
element.addEventListener('click', this.onClick.bind(this), false);
};
MyObject.prototype.onClick = function(e) {
var t=this; //do something with [t]...
//without bind the context of this function wouldn't be a MyObject
//instance as you would normally expect.
};
I use it extensively in Node.js for async callbacks that I want to pass a member method for, but still want the context to be the instance that started the async action.
A simple, naive implementation of bind would be like:
Function.prototype.bind = function(ctx) {
var fn = this;
return function() {
fn.apply(ctx, arguments);
};
};
There is more to it (like passing other args), but you can read more about it and see the real implementation on the MDN.

They all attach this into function (or object) and the difference is in the function invocation (see below).
call attaches this into function and executes the function immediately:
var person = {
name: "James Smith",
hello: function(thing) {
console.log(this.name + " says hello " + thing);
}
}
person.hello("world"); // output: "James Smith says hello world"
person.hello.call({ name: "Jim Smith" }, "world"); // output: "Jim Smith says hello world"
bind attaches this into function and it needs to be invoked separately like this:
var person = {
name: "James Smith",
hello: function(thing) {
console.log(this.name + " says hello " + thing);
}
}
person.hello("world"); // output: "James Smith says hello world"
var helloFunc = person.hello.bind({ name: "Jim Smith" });
helloFunc("world"); // output: Jim Smith says hello world"
or like this:
...
var helloFunc = person.hello.bind({ name: "Jim Smith" }, "world");
helloFunc(); // output: Jim Smith says hello world"
apply is similar to call except that it takes an array-like object instead of listing the arguments out one at a time:
function personContainer() {
var person = {
name: "James Smith",
hello: function() {
console.log(this.name + " says hello " + arguments[1]);
}
}
person.hello.apply(person, arguments);
}
personContainer("world", "mars"); // output: "James Smith says hello mars", note: arguments[0] = "world" , arguments[1] = "mars"

Answer in SIMPLEST form
Call invokes the function and allows you to pass in arguments one by
one.
Apply invokes the function and allows you to pass in arguments
as an array.
Bind returns a new function, allowing you to pass in a
this array and any number of arguments.
Apply vs. Call vs. Bind Examples
Call
var person1 = {firstName: 'Jon', lastName: 'Kuperman'};
var person2 = {firstName: 'Kelly', lastName: 'King'};
function say(greeting) {
console.log(greeting + ' ' + this.firstName + ' ' + this.lastName);
}
say.call(person1, 'Hello'); // Hello Jon Kuperman
say.call(person2, 'Hello'); // Hello Kelly King
Apply
var person1 = {firstName: 'Jon', lastName: 'Kuperman'};
var person2 = {firstName: 'Kelly', lastName: 'King'};
function say(greeting) {
console.log(greeting + ' ' + this.firstName + ' ' + this.lastName);
}
say.apply(person1, ['Hello']); // Hello Jon Kuperman
say.apply(person2, ['Hello']); // Hello Kelly King
Bind
var person1 = {firstName: 'Jon', lastName: 'Kuperman'};
var person2 = {firstName: 'Kelly', lastName: 'King'};
function say() {
console.log('Hello ' + this.firstName + ' ' + this.lastName);
}
var sayHelloJon = say.bind(person1);
var sayHelloKelly = say.bind(person2);
sayHelloJon(); // Hello Jon Kuperman
sayHelloKelly(); // Hello Kelly King
When To Use Each
Call and apply are pretty interchangeable. Just decide whether it’s easier to send in an array or a comma separated list of arguments.
I always remember which one is which by remembering that Call is for comma (separated list) and Apply is for Array.
Bind is a bit different. It returns a new function. Call and Apply execute the current function immediately.
Bind is great for a lot of things. We can use it to curry functions like in the above example. We can take a simple hello function and turn it into a helloJon or helloKelly. We can also use it for events like onClick where we don’t know when they’ll be fired but we know what context we want them to have.
Reference: codeplanet.io

I created this comparison between function objects, function calls, call/apply and bind a while ago:
.bind allows you to set the this value now while allowing you to execute the function in the future, because it returns a new function object.

TL;DR:
In simple words, bind creates the function, call and apply executes the function whereas apply expects the parameters in array
Full Explanation
Assume we have multiplication function
function multiplication(a,b){
console.log(a*b);
}
Lets create some standard functions using bind
var multiby2 = multiplication.bind(this,2);
Now multiby2(b) is equal to multiplication(2,b);
multiby2(3); //6
multiby2(4); //8
What if I pass both the parameters in bind
var getSixAlways = multiplication.bind(this,3,2);
Now getSixAlways() is equal to multiplication(3,2);
getSixAlways();//6
even passing parameter returns 6;
getSixAlways(12); //6
var magicMultiplication = multiplication.bind(this);
This create a new multiplication function and assigns it to magicMultiplication.
Oh no, we are hiding the multiplication functionality into magicMultiplication.
calling
magicMultiplication returns a blank function b()
on execution it works fine
magicMultiplication(6,5); //30
How about call and apply?
magicMultiplication.call(this,3,2); //6
magicMultiplication.apply(this,[5,2]); //10

It allows to set the value for this independent of how the function is called. This is very useful when working with callbacks:
function sayHello(){
alert(this.message);
}
var obj = {
message : "hello"
};
setTimeout(sayHello.bind(obj), 1000);
To achieve the same result with call would look like this:
function sayHello(){
alert(this.message);
}
var obj = {
message : "hello"
};
setTimeout(function(){sayHello.call(obj)}, 1000);

The main concept behind all this methods is Function burrowing.
Function borrowing allows us to use the methods of one object on a different object without having to make a copy of that method and maintain it in two separate places. It is accomplished through the use of . call() , . apply() , or . bind() , all of which exist to explicitly set this on the method we are borrowing
Call invokes the function immediately and allows you to pass in arguments one by
one
Apply invokes the function immediately and allows you to pass in arguments
as an array.
Bind returns a new function, and you can invoke/call it anytime you want by invoking a function.
Below is an example of all this methods
let name = {
firstname : "Arham",
lastname : "Chowdhury",
}
printFullName = function(hometown,company){
console.log(this.firstname + " " + this.lastname +", " + hometown + ", " + company)
}
CALL
the first argument e.g name inside call method is always a reference
to (this) variable and latter will be function variable
printFullName.call(name,"Mumbai","Taufa"); //Arham Chowdhury, Mumbai, Taufa
APPLY
apply method is same as the call method
the only diff is that, the function arguments are passed in Array list
printFullName.apply(name, ["Mumbai","Taufa"]); //Arham Chowdhury, Mumbai, Taufa
BIND
bind method is same as call except that ,the bind returns a function that can be used later by invoking it (does'nt call it immediately)
let printMyNAme = printFullName.bind(name,"Mumbai","Taufa");
printMyNAme(); //Arham Chowdhury, Mumbai, Taufa
printMyNAme() is the function which invokes the function
below is the link for jsfiddle
https://codepen.io/Arham11/pen/vYNqExp

Both Function.prototype.call() and Function.prototype.apply() call a function with a given this value, and return the return value of that function.
Function.prototype.bind(), on the other hand, creates a new function with a given this value, and returns that function without executing it.
So, let's take a function that looks like this :
var logProp = function(prop) {
console.log(this[prop]);
};
Now, let's take an object that looks like this :
var Obj = {
x : 5,
y : 10
};
We can bind our function to our object like this :
Obj.log = logProp.bind(Obj);
Now, we can run Obj.log anywhere in our code :
Obj.log('x'); // Output : 5
Obj.log('y'); // Output : 10
Where it really gets interesting, is when you not only bind a value for this, but also for for its argument prop :
Obj.logX = logProp.bind(Obj, 'x');
Obj.logY = logProp.bind(Obj, 'y');
We can now do this :
Obj.logX(); // Output : 5
Obj.logY(); // Output : 10

bind: It binds the function with provided value and context but it does not executes the function. To execute function you need to call the function.
call: It executes the function with provided context and parameter.
apply: It executes the function with provided context and
parameter as array.

Here is one good article to illustrate the difference among bind(), apply() and call(), summarize it as below.
bind() allows us to easily set which specific object will be bound to this when a function or method is invoked.
// This data variable is a global variable​
var data = [
{name:"Samantha", age:12},
{name:"Alexis", age:14}
]
var user = {
// local data variable​
data :[
{name:"T. Woods", age:37},
{name:"P. Mickelson", age:43}
],
showData:function (event) {
var randomNum = ((Math.random () * 2 | 0) + 1) - 1; // random number between 0 and 1​
console.log (this.data[randomNum].name + " " + this.data[randomNum].age);
}
}
// Assign the showData method of the user object to a variable​
var showDataVar = user.showData;
showDataVar (); // Samantha 12 (from the global data array, not from the local data array)​
/*
This happens because showDataVar () is executed as a global function and use of this inside
showDataVar () is bound to the global scope, which is the window object in browsers.
*/
// Bind the showData method to the user object​
var showDataVar = user.showData.bind (user);
// Now the we get the value from the user object because the this keyword is bound to the user object​
showDataVar (); // P. Mickelson 43​
bind() allow us to borrow methods
// Here we have a cars object that does not have a method to print its data to the console​
var cars = {
data:[
{name:"Honda Accord", age:14},
{name:"Tesla Model S", age:2}
]
}
// We can borrow the showData () method from the user object we defined in the last example.​
// Here we bind the user.showData method to the cars object we just created.​
cars.showData = user.showData.bind (cars);
cars.showData (); // Honda Accord 14​
One problem with this example is that we are adding a new method showData on the cars object and
we might not want to do that just to borrow a method because the cars object might already have a property or method name showData.
We don’t want to overwrite it accidentally. As we will see in our discussion of Apply and Call below,
it is best to borrow a method using either the Apply or Call method.
bind() allow us to curry a function
Function Currying, also known as partial function application, is the use of a
function (that accept one or more arguments) that returns a new function with some of the arguments already set.
function greet (gender, age, name) {
// if a male, use Mr., else use Ms.​
var salutation = gender === "male" ? "Mr. " : "Ms. ";
if (age > 25) {
return "Hello, " + salutation + name + ".";
}else {
return "Hey, " + name + ".";
}
}
We can use bind() to curry this greet function
// So we are passing null because we are not using the "this" keyword in our greet function.
var greetAnAdultMale = greet.bind (null, "male", 45);
greetAnAdultMale ("John Hartlove"); // "Hello, Mr. John Hartlove."
var greetAYoungster = greet.bind (null, "", 16);
greetAYoungster ("Alex"); // "Hey, Alex."​
greetAYoungster ("Emma Waterloo"); // "Hey, Emma Waterloo."
apply() or call() to set this value
The apply, call, and bind methods are all used to set the this value when invoking a method, and they do it in slightly
different ways to allow use direct control and versatility in our JavaScript code.
The apply and call methods are almost identical when setting the this value except that you pass the function parameters to apply () as an array, while you have to list the parameters individually to pass them to the call () method.
Here is one example to use call or apply to set this in the callback function.
// Define an object with some properties and a method​
// We will later pass the method as a callback function to another function​
var clientData = {
id: 094545,
fullName: "Not Set",
// setUserName is a method on the clientData object​
setUserName: function (firstName, lastName) {
// this refers to the fullName property in this object​
this.fullName = firstName + " " + lastName;
}
};
function getUserInput (firstName, lastName, callback, callbackObj) {
// The use of the Apply method below will set the "this" value to callbackObj​
callback.apply (callbackObj, [firstName, lastName]);
}
// The clientData object will be used by the Apply method to set the "this" value​
getUserInput ("Barack", "Obama", clientData.setUserName, clientData);
// the fullName property on the clientData was correctly set​
console.log (clientData.fullName); // Barack Obama
Borrow functions with apply or call
Borrow Array methods
Let’s create an array-like object and borrow some array methods to operate on the our array-like object.
// An array-like object: note the non-negative integers used as keys​
var anArrayLikeObj = {0:"Martin", 1:78, 2:67, 3:["Letta", "Marieta", "Pauline"], length:4 };
// Make a quick copy and save the results in a real array:
// First parameter sets the "this" value​
var newArray = Array.prototype.slice.call (anArrayLikeObj, 0);
console.log (newArray); // ["Martin", 78, 67, Array[3]]​
// Search for "Martin" in the array-like object​
console.log (Array.prototype.indexOf.call (anArrayLikeObj, "Martin") === -1 ? false : true); // true​
Another common case is that convert arguments to array as following
// We do not define the function with any parameters, yet we can get all the arguments passed to it​
function doSomething () {
var args = Array.prototype.slice.call (arguments);
console.log (args);
}
doSomething ("Water", "Salt", "Glue"); // ["Water", "Salt", "Glue"]
Borrow other methods
var gameController = {
scores :[20, 34, 55, 46, 77],
avgScore:null,
players :[
{name:"Tommy", playerID:987, age:23},
{name:"Pau", playerID:87, age:33}
]
}
var appController = {
scores :[900, 845, 809, 950],
avgScore:null,
avg :function () {
var sumOfScores = this.scores.reduce (function (prev, cur, index, array) {
return prev + cur;
});
this.avgScore = sumOfScores / this.scores.length;
}
}
// Note that we are using the apply () method, so the 2nd argument has to be an array​
appController.avg.apply (gameController);
console.log (gameController.avgScore); // 46.4​
// appController.avgScore is still null; it was not updated, only gameController.avgScore was updated​
console.log (appController.avgScore); // null​
Use apply() to execute variable-arity function
The Math.max is one example of variable-arity function,
// We can pass any number of arguments to the Math.max () method​
console.log (Math.max (23, 11, 34, 56)); // 56
But what if we have an array of numbers to pass to Math.max? We cannot do this:
var allNumbers = [23, 11, 34, 56];
// We cannot pass an array of numbers to the the Math.max method like this​
console.log (Math.max (allNumbers)); // NaN
This is where the apply () method helps us execute variadic functions. Instead of the above, we have to pass the array of numbers using apply () thus:
var allNumbers = [23, 11, 34, 56];
// Using the apply () method, we can pass the array of numbers:
console.log (Math.max.apply (null, allNumbers)); // 56

The basic difference between Call, Apply and Bind are:
Bind will be used if you want your execution context to come later in the picture.
Ex:
var car = {
registrationNumber: "007",
brand: "Mercedes",
displayDetails: function(ownerName){
console.log(ownerName + ' this is your car ' + '' + this.registrationNumber + " " + this.brand);
}
}
car.displayDetails('Nishant'); // **Nishant this is your car 007 Mercedes**
Let's say i want use this method in some other variable
var car1 = car.displayDetails('Nishant');
car1(); // undefined
To use the reference of car in some other variable you should use
var car1 = car.displayDetails.bind(car, 'Nishant');
car1(); // Nishant this is your car 007 Mercedes
Let's talk about more extensive use of bind function
var func = function() {
console.log(this)
}.bind(1);
func();
// Number: 1
Why? Because now func is bind with Number 1, if we don't use bind in that case it will point to Global Object.
var func = function() {
console.log(this)
}.bind({});
func();
// Object
Call, Apply are used when you want to execute the statement at the same time.
var Name = {
work: "SSE",
age: "25"
}
function displayDetails(ownerName) {
console.log(ownerName + ", this is your name: " + 'age' + this.age + " " + 'work' + this.work);
}
displayDetails.call(Name, 'Nishant')
// Nishant, this is your name: age25 workSSE
// In apply we pass an array of arguments
displayDetails.apply(Name, ['Nishant'])
// Nishant, this is your name: age25 workSSE

call/apply executes function immediately:
func.call(context, arguments);
func.apply(context, [argument1,argument2,..]);
bind doesn't execute function immediately, but returns wrapped apply function (for later execution):
function bind(func, context) {
return function() {
return func.apply(context, arguments);
};
}

Call apply and bind. and how they are different.
Lets learn call and apply using any daily terminology.
You have three automobiles your_scooter , your_car and your_jet which start with the same mechanism (method).
We created an object automobile with a method push_button_engineStart.
var your_scooter, your_car, your_jet;
var automobile = {
push_button_engineStart: function (runtime){
console.log(this.name + "'s" + ' engine_started, buckle up for the ride for ' + runtime + " minutes");
}
}
Lets understand when is call and apply used. Lets suppose that you are an engineer and you have your_scooter, your_car and your_jet which did not come with a push_button_engine_start and you wish to use a third party push_button_engineStart.
If you run the following lines of code, they will give an error. WHY?
//your_scooter.push_button_engineStart();
//your_car.push_button_engineStart();
//your_jet.push_button_engineStart();
automobile.push_button_engineStart.apply(your_scooter,[20]);
automobile.push_button_engineStart.call(your_jet,10);
automobile.push_button_engineStart.call(your_car,40);
So the above example is successfully gives your_scooter, your_car, your_jet a feature from automobile object.
Let's dive deeper
Here we will split the above line of code.
automobile.push_button_engineStart is helping us to get the method being used.
Further we use apply or call using the dot notation.
automobile.push_button_engineStart.apply()
Now apply and call accept two parameters.
context
arguments
So here we set the context in the final line of code.
automobile.push_button_engineStart.apply(your_scooter,[20])
Difference between call and apply is just that apply accepts parameters in the form of an array while call simply can accept a comma separated list of arguments.
what is JS Bind function?
A bind function is basically which binds the context of something and then stores it into a variable for execution at a later stage.
Let's make our previous example even better. Earlier we used a method belonging to the automobile object and used it to equip your_car, your_jet and your_scooter. Now lets imagine we want to give a separate push_button_engineStart separately to start our automobiles individually at any later stage of the execution we wish.
var scooty_engineStart = automobile.push_button_engineStart.bind(your_scooter);
var car_engineStart = automobile.push_button_engineStart.bind(your_car);
var jet_engineStart = automobile.push_button_engineStart.bind(your_jet);
setTimeout(scooty_engineStart,5000,30);
setTimeout(car_engineStart,10000,40);
setTimeout(jet_engineStart,15000,5);
still not satisfied?
Let's make it clear as teardrop. Time to experiment. We will go back to call and apply function application and try storing the value of the function as a reference.
The experiment below fails because call and apply are invoked immediately, hence, we never get to the stage of storing a reference in a variable which is where bind function steals the show
var test_function = automobile.push_button_engineStart.apply(your_scooter);

Syntax
call(thisArg, arg1, arg2, ...)
apply(thisArg, argsArray)
bind(thisArg[, arg1[, arg2[, ...]]])
Here
thisArg is the object
argArray is an array object
arg1, arg2, arg3,... are additional arguments
function printBye(message1, message2){
console.log(message1 + " " + this.name + " "+ message2);
}
var par01 = { name:"John" };
var msgArray = ["Bye", "Never come again..."];
printBye.call(par01, "Bye", "Never come again...");
//Bye John Never come again...
printBye.call(par01, msgArray);
//Bye,Never come again... John undefined
//so call() doesn't work with array and better with comma seperated parameters
//printBye.apply(par01, "Bye", "Never come again...");//Error
printBye.apply(par01, msgArray);
//Bye John Never come again...
var func1 = printBye.bind(par01, "Bye", "Never come again...");
func1();//Bye John Never come again...
var func2 = printBye.bind(par01, msgArray);
func2();//Bye,Never come again... John undefined
//so bind() doesn't work with array and better with comma seperated parameters

JavaScript Call()
const person = {
name: "Lokamn",
dob: 12,
print: function (value,value2) {
console.log(this.dob+value+value2)
}
}
const anotherPerson= {
name: "Pappu",
dob: 12,
}
person.print.call(anotherPerson,1,2)
JavaScript apply()
name: "Lokamn",
dob: 12,
print: function (value,value2) {
console.log(this.dob+value+value2)
}
}
const anotherPerson= {
name: "Pappu",
dob: 12,
}
person.print.apply(anotherPerson,[1,2])
**call and apply function are difference call take separate argument but apply take array
like:[1,2,3]
**
JavaScript bind()
name: "Lokamn",
dob: 12,
anotherPerson: {
name: "Pappu",
dob: 12,
print2: function () {
console.log(this)
}
}
}
var bindFunction = person.anotherPerson.print2.bind(person)
bindFunction()

Call: call invokes the function and allows you to pass arguments one by one
Apply: Apply invokes the function and allows you to pass arguments as an array
Bind: Bind returns a new function, allowing you to pass in a this array and any number of arguments.
var person1 = {firstName: 'Raju', lastName: 'king'};
var person2 = {firstName: 'chandu', lastName: 'shekar'};
function greet(greeting) {
console.log(greeting + ' ' + this.firstName + ' ' + this.lastName);
}
function greet2(greeting) {
console.log( 'Hello ' + this.firstName + ' ' + this.lastName);
}
greet.call(person1, 'Hello'); // Hello Raju king
greet.call(person2, 'Hello'); // Hello chandu shekar
greet.apply(person1, ['Hello']); // Hello Raju king
greet.apply(person2, ['Hello']); // Hello chandu shekar
var greetRaju = greet2.bind(person1);
var greetChandu = greet2.bind(person2);
greetRaju(); // Hello Raju king
greetChandu(); // Hello chandu shekar

call() :-- Here we pass the function arguments individually, not in an array format
var obj = {name: "Raushan"};
var greeting = function(a,b,c) {
return "Welcome "+ this.name + " to "+ a + " " + b + " in " + c;
};
console.log(greeting.call(obj, "USA", "INDIA", "ASIA"));
apply() :-- Here we pass the function arguments in an array format
var obj = {name: "Raushan"};
var cal = function(a,b,c) {
return this.name +" you got " + a+b+c;
};
var arr =[1,2,3]; // array format for function arguments
console.log(cal.apply(obj, arr));
bind() :--
var obj = {name: "Raushan"};
var cal = function(a,b,c) {
return this.name +" you got " + a+b+c;
};
var calc = cal.bind(obj);
console.log(calc(2,3,4));

Imagine, bind is not available.
you can easily construct it as follow :
var someFunction=...
var objToBind=....
var bindHelper = function (someFunction, objToBind) {
return function() {
someFunction.apply( objToBind, arguments );
};
}
bindHelper(arguments);

function sayHello() {
//alert(this.message);
return this.message;
}
var obj = {
message: "Hello"
};
function x(country) {
var z = sayHello.bind(obj);
setTimeout(y = function(w) {
//'this' reference not lost
return z() + ' ' + country + ' ' + w;
}, 1000);
return y;
}
var t = x('India')('World');
document.getElementById("demo").innerHTML = t;

Use bind for future calls to the function. Both apply and call invoke the function.
bind() also allows for additional arguments to be perpended to the args array.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind

In simple terms, all methods are used to set the context(this) explicitly in the regular function
Call: call invokes the function on given context and allows to pass arguments one by one
Apply: apply invokes the function on given context and allows to pass arguments as an array
Bind: bind returns a new function by setting the provided context, and allows to pass arguments one by one
Notes:
Call and Apply both are similar only difference is the way they expect arguments
The mentioned methods do not work with arrow function

The first difference between call(), apply(), and bind() methods in JavaScript is their time of execution!
call() and apply() being similar are executed instantly, whereas, bind() creates a new function which we have to explicitly call at any later point of time!
Another difference is, that while passing arguments, call() allows us to pass one by one separated by commas, apply() allows us to pass as an array of arguments, and bind() allows us to do both!
I have attached the example code below!
const person = {
fullName : function (randomMessage) {
return `Hello, ${this.firstName} ${this.lastName} ${randomMessage}`;
}
}
const personOne = {
firstName : "John",
lastName : "Doe"
}
const personTwo = {
firstName : "Jack",
lastName : "Adhikari"
}
let fullNameBind = person.fullName.bind(personOne, "--Binding");
let fullNameCall = person.fullName.call({firstName : "Sarah", lastName: "Holmes"}, "--Calling");
let fullNameApply = person.fullName.apply(personTwo, ["--Applying"]);
console.log(fullNameBind());
console.log(fullNameCall);
console.log(fullNameApply);

I think the same places of them are: all of them can change the this value of a function.The differences of them are: the bind function will return a new function as a result; the call and apply methods will execute the function immediately, but apply can accept a array as params,and it will parse the array separated.And also, the bind function can be Currying.

bind function should be use when we want to assign a function with particular context for eg.
var demo = {
getValue : function(){
console.log('demo object get value function')
}
setValue : function(){
setTimeout(this.getValue.bind(this),1000)
}
}
in above example if we call demo.setValue() function and pass this.getValue function directly then it doesn't call demo.setValue function directly because this in setTimeout refers to window object so we need to pass demo object context to this.getValue function using bind. it means we only passing function with the context of demo object not actully calling function.
Hope u understand .
for more information please refer
javascript bind function know in detail

Related

What does binding a function to 'this' do in the constructor? [duplicate]

What is the use of bind() in JavaScript?
Bind creates a new function that will force the this inside the function to be the parameter passed to bind().
Here's an example that shows how to use bind to pass a member method around that has the correct this:
var myButton = {
content: 'OK',
click() {
console.log(this.content + ' clicked');
}
};
myButton.click();
var looseClick = myButton.click;
looseClick(); // not bound, 'this' is not myButton - it is the globalThis
var boundClick = myButton.click.bind(myButton);
boundClick(); // bound, 'this' is myButton
Which prints out:
OK clicked
undefined clicked
OK clicked
You can also add extra parameters after the 1st (this) parameter and bind will pass in those values to the original function. Any additional parameters you later pass to the bound function will be passed in after the bound parameters:
// Example showing binding some parameters
var sum = function(a, b) {
return a + b;
};
var add5 = sum.bind(null, 5);
console.log(add5(10));
Which prints out:
15
Check out JavaScript Function bind for more info and interactive examples.
Update: ECMAScript 2015 adds support for => functions. => functions are more compact and do not change the this pointer from their defining scope, so you may not need to use bind() as often. For example, if you wanted a function on Button from the first example to hook up the click callback to a DOM event, the following are all valid ways of doing that:
var myButton = {
... // As above
hookEvent(element) {
// Use bind() to ensure 'this' is the 'this' inside click()
element.addEventListener('click', this.click.bind(this));
}
};
Or:
var myButton = {
... // As above
hookEvent(element) {
// Use a new variable for 'this' since 'this' inside the function
// will not be the 'this' inside hookEvent()
var me = this;
element.addEventListener('click', function() { me.click() });
}
};
Or:
var myButton = {
... // As above
hookEvent(element) {
// => functions do not change 'this', so you can use it directly
element.addEventListener('click', () => this.click());
}
};
The simplest use of bind() is to make a function that, no matter
how it is called, is called with a particular this value.
x = 9;
var module = {
x: 81,
getX: function () {
return this.x;
}
};
module.getX(); // 81
var getX = module.getX;
getX(); // 9, because in this case, "this" refers to the global object
// create a new function with 'this' bound to module
var boundGetX = getX.bind(module);
boundGetX(); // 81
Please refer to this link on MDN Web Docs for more information:
Function.prototype.bind()
bind allows-
set the value of "this" to an specific object. This becomes very helpful as sometimes this is not what is intended.
reuse methods
curry a function
For example, you have a function to deduct monthly club fees
function getMonthlyFee(fee){
var remaining = this.total - fee;
this.total = remaining;
return this.name +' remaining balance:'+remaining;
}
Now you want to reuse this function for a different club member. Note that the monthly fee will vary from member to member.
Let's imagine Rachel has a balance of 500, and a monthly membership fee of 90.
var rachel = {name:'Rachel Green', total:500};
Now, create a function that can be used again and again to deduct the fee from her account every month
//bind
var getRachelFee = getMonthlyFee.bind(rachel, 90);
//deduct
getRachelFee();//Rachel Green remaining balance:410
getRachelFee();//Rachel Green remaining balance:320
Now, the same getMonthlyFee function could be used for another member with a different membership fee. For Example, Ross Geller has a 250 balance and a monthly fee of 25
var ross = {name:'Ross Geller', total:250};
//bind
var getRossFee = getMonthlyFee.bind(ross, 25);
//deduct
getRossFee(); //Ross Geller remaining balance:225
getRossFee(); //Ross Geller remaining balance:200
From the MDN docs on Function.prototype.bind() :
The bind() method creates a new function that, when called, has its
this keyword set to the provided value, with a given sequence of
arguments preceding any provided when the new function is called.
So, what does that mean?!
Well, let's take a function that looks like this :
var logProp = function(prop) {
console.log(this[prop]);
};
Now, let's take an object that looks like this :
var Obj = {
x : 5,
y : 10
};
We can bind our function to our object like this :
Obj.log = logProp.bind(Obj);
Now, we can run Obj.log anywhere in our code :
Obj.log('x'); // Output : 5
Obj.log('y'); // Output : 10
This works, because we bound the value of this to our object Obj.
Where it really gets interesting, is when you not only bind a value for this, but also for its argument prop :
Obj.logX = logProp.bind(Obj, 'x');
Obj.logY = logProp.bind(Obj, 'y');
We can now do this :
Obj.logX(); // Output : 5
Obj.logY(); // Output : 10
Unlike with Obj.log, we do not have to pass x or y, because we passed those values when we did our binding.
Variables has local and global scopes. Let's suppose that we have two variables with the same name. One is globally defined and the other is defined inside a function closure and we want to get the variable value which is inside the function closure. In that case we use this bind() method. Please see the simple example below:
var x = 9; // this refers to global "window" object here in the browser
var person = {
x: 81,
getX: function() {
return this.x;
}
};
var y = person.getX; // It will return 9, because it will call global value of x(var x=9).
var x2 = y.bind(person); // It will return 81, because it will call local value of x, which is defined in the object called person(x=81).
document.getElementById("demo1").innerHTML = y();
document.getElementById("demo2").innerHTML = x2();
<p id="demo1">0</p>
<p id="demo2">0</p>
Summary:
The bind() method takes an object as an first argument and creates a new function. When the function is invoked the value of this in the function body will be the object which was passed in as an argument in the bind() function.
How does this work in JS anyway
The value of this in javascript is dependent always depends on what Object the function is called. The value of this always refers to the object left of the dot from where is the function is called. In case of the global scope this is window (or global in nodeJS). Only call, apply and bind can alter the this binding differently. Here is an example to show how the this keyword works:
let obj = {
prop1: 1,
func: function () { console.log(this); }
}
obj.func(); // obj left of the dot so this refers to obj
const customFunc = obj.func; // we store the function in the customFunc obj
customFunc(); // now the object left of the dot is window,
// customFunc() is shorthand for window.customFunc()
// Therefore window will be logged
How is bind used?
Bind can help in overcoming difficulties with the this keyword by having a fixed object where this will refer to. For example:
var name = 'globalName';
const obj = {
name: 'myName',
sayName: function () { console.log(this.name);}
}
const say = obj.sayName; // we are merely storing the function the value of this isn't magically transferred
say(); // now because this function is executed in global scope this will refer to the global var
const boundSay = obj.sayName.bind(obj); // now the value of this is bound to the obj object
boundSay(); // Now this will refer to the name in the obj object: 'myName'
Once the function is bound to a particular this value we can pass it around and even put it on properties on other objects. The value of this will remain the same.
The bind() method creates a new function instance whose this value is bound to the value that was passed into bind().
For example:
window.color = "red";
var o = { color: "blue" };
function sayColor(){
alert(this.color);
}
var objectSayColor = sayColor.bind(o);
objectSayColor(); //blue
Here, a new function called objectSayColor() is created from sayColor() by calling bind() and passing in the object o. The objectSayColor() function has a this value equivalent to o, so calling the function, even as a global call, results in the string “blue” being displayed.
Reference : Nicholas C. Zakas - PROFESSIONAL JAVASCRIPT® FOR WEB DEVELOPERS
I will explain bind theoretically as well as practically
bind in javascript is a method -- Function.prototype.bind . bind is a method. It is called on function prototype. This method creates a function whose body is similar to the function on which it is called but the 'this' refers to the first parameter passed to the bind method. Its syntax is
var bindedFunc = Func.bind(thisObj,optionsArg1,optionalArg2,optionalArg3,...);
Example:--
var checkRange = function(value){
if(typeof value !== "number"){
return false;
}
else {
return value >= this.minimum && value <= this.maximum;
}
}
var range = {minimum:10,maximum:20};
var boundedFunc = checkRange.bind(range); //bounded Function. this refers to range
var result = boundedFunc(15); //passing value
console.log(result) // will give true;
Creating a new Function by Binding Arguments to Values
The bind method creates a new function from another function with one or more arguments bound to specific values, including the implicit this argument.
Partial Application
This is an example of partial application. Normally we supply a function with all of its arguments which yields a value. This is known as function application. We are applying the function to its arguments.
A Higher Order Function (HOF)
Partial application is an example of a higher order function (HOF) because it yields a new function with a fewer number of argument.
Binding Multiple Arguments
You can use bind to transform functions with multiple arguments into new functions.
function multiply(x, y) {
return x * y;
}
let multiplyBy10 = multiply.bind(null, 10);
console.log(multiplyBy10(5));
Converting from Instance Method to Static Function
In the most common use case, when called with one argument the bind method will create a new function that has the this value bound to a specific value. In effect this transforms an instance method to a static method.
function Multiplier(factor) {
this.factor = factor;
}
Multiplier.prototype.multiply = function(x) {
return this.factor * x;
}
function ApplyFunction(func, value) {
return func(value);
}
var mul = new Multiplier(5);
// Produces garbage (NaN) because multiplying "undefined" by 10
console.log(ApplyFunction(mul.multiply, 10));
// Produces expected result: 50
console.log(ApplyFunction(mul.multiply.bind(mul), 10));
Implementing a Stateful CallBack
The following example shows how using binding of this can enable an object method to act as a callback that can easily update the state of an object.
function ButtonPressedLogger()
{
this.count = 0;
this.onPressed = function() {
this.count++;
console.log("pressed a button " + this.count + " times");
}
for (let d of document.getElementsByTagName("button"))
d.onclick = this.onPressed.bind(this);
}
new ButtonPressedLogger();
<button>press me</button>
<button>no press me</button>
As mentioned, Function.bind() lets you specify the context that the function will execute in (that is, it lets you pass in what object the this keyword will resolve to in the body of the function.
A couple of analogous toolkit API methods that perform a similar service:
jQuery.proxy()
Dojo.hitch()
Bind Method
A bind implementation might look something like so:
Function.prototype.bind = function () {
const self = this;
const args = [...arguments];
const context = args.shift();
return function () {
return self.apply(context, args.concat([...arguments]));
};
};
The bind function can take any number of arguments and return a new function.
The new function will call the original function using the JS Function.prototype.apply method.The apply method will use the first argument passed to the target function as its context (this), and the second array argument of the apply method will be a combination of the rest of the arguments from the target function, concat with the arguments used to call the return function (in that order).
An example can look something like so:
function Fruit(emoji) {
this.emoji = emoji;
}
Fruit.prototype.show = function () {
console.log(this.emoji);
};
const apple = new Fruit('🍎');
const orange = new Fruit('🍊');
apple.show(); // 🍎
orange.show(); // 🍊
const fruit1 = apple.show;
const fruit2 = apple.show.bind();
const fruit3 = apple.show.bind(apple);
const fruit4 = apple.show.bind(orange);
fruit1(); // undefined
fruit2(); // undefined
fruit3(); // 🍎
fruit4(); // 🍊
/**
* Bind is a method inherited from Function.prototype same like call and apply
* It basically helps to bind a function to an object's context during initialisation
*
* */
window.myname = "Jineesh";
var foo = function(){
return this.myname;
};
//IE < 8 has issues with this, supported in ecmascript 5
var obj = {
myname : "John",
fn:foo.bind(window)// binds to window object
};
console.log( obj.fn() ); // Returns Jineesh
Consider the Simple Program listed below,
//we create object user
let User = { name: 'Justin' };
//a Hello Function is created to Alert the object User
function Hello() {
alert(this.name);
}
//since there the value of this is lost we need to bind user to use this keyword
let user = Hello.bind(User);
user();
//we create an instance to refer the this keyword (this.name);
Simple Explanation:
bind() create a new function, a new reference at a function it returns to you.
In parameter after this keyword, you pass in the parameter you want to preconfigure. Actually it does not execute immediately, just prepares for execution.
You can preconfigure as many parameters as you want.
Simple Example to understand bind:
function calculate(operation) {
if (operation === 'ADD') {
alert('The Operation is Addition');
} else if (operation === 'SUBTRACT') {
alert('The Operation is Subtraction');
}
}
addBtn.addEventListener('click', calculate.bind(this, 'ADD'));
subtractBtn.addEventListener('click', calculate.bind(this, 'SUBTRACT'));
The bind function creates a new function with the same function body as the function it is calling .It is called with the this argument .why we use bind fun. : when every time a new instance is created and we have to use first initial instance then we use bind fun.We can't override the bind fun.simply it stores the initial object of the class.
setInterval(this.animate_to.bind(this), 1000/this.difference);
function.prototype.bind() accepts an Object.
It binds the calling function to the passed Object and the returns
the same.
When an object is bound to a function, it means you will be able to
access the values of that object from within the function using
'this' keyword.
It can also be said as,
function.prototype.bind() is used to provide/change the context of a
function.
let powerOfNumber = function(number) {
let product = 1;
for(let i=1; i<= this.power; i++) {
product*=number;
}
return product;
}
let powerOfTwo = powerOfNumber.bind({power:2});
alert(powerOfTwo(2));
let powerOfThree = powerOfNumber.bind({power:3});
alert(powerOfThree(2));
let powerOfFour = powerOfNumber.bind({power:4});
alert(powerOfFour(2));
Let us try to understand this.
let powerOfNumber = function(number) {
let product = 1;
for (let i = 1; i <= this.power; i++) {
product *= number;
}
return product;
}
Here, in this function, this corresponds to the object bound to the function powerOfNumber. Currently we don't have any function that is bound to this function.
Let us create a function powerOfTwo which will find the second power of a number using the above function.
let powerOfTwo = powerOfNumber.bind({power:2});
alert(powerOfTwo(2));
Here the object {power : 2} is passed to powerOfNumber function using bind.
The bind function binds this object to the powerOfNumber() and returns the below function to powerOfTwo. Now, powerOfTwo looks like,
let powerOfNumber = function(number) {
let product = 1;
for(let i=1; i<=2; i++) {
product*=number;
}
return product;
}
Hence, powerOfTwo will find the second power.
Feel free to check this out.
bind() function in Javascript
The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.
An example for the first part
grabbed from react package useSt8
import { useState } from "react"
function st8() {
switch(arguments.length) {
case 0: return this[0]
case 1: return void this[1](arguments[0])
default: throw new Error("Expected 0 or 1 arguments")
}
}
function useSt8(initial) {
// this in st8 will be something like [state, setSatate]
return st8.bind(useState(initial))
}
// usage
function Counter() {
const count = useSt8(0);
return (
<>
Count: {count()}
<button onClick={() => count(0)}>Reset</button>
<button onClick={() => count(prevCount => prevCount + 1)}>inc</button>
</>
);
}
An example for the second part
const add = (a, b) => a+b
someThis = this
// new function with this value equal to someThis
add5 = add.bind(someThis, 5)
add5(10) // 15
// we don't use this in add decelartion so this will work too.
add10 = add.bind(null, 10)
add10(5) // 15
Here's the simplest possible explanation:
Say you have a function
function _loop(n) { console.log("so: " + n) }
obviously you can call it like _loop(69) as usual.
Rewrite like this:
var _loop = function() { console.log("so: " + this.n) }
Notice there are now
no arguments as such
you use "this. " to get to the named arguments
You can now call the function like this:
_loop.bind( {"n": 420} )
That's it.
Most typical use case:
A really typical use is when you need to add an argument to a callback.
Callbacks can't have arguments.
So just "rewrite" the callback as above.
Simple example
function lol(second, third) {
console.log(this.first, second, third);
}
lol(); // undefined, undefined, undefined
lol('1'); // undefined, "1", undefined
lol('1', '2'); // undefined, "1", "2"
lol.call({first: '1'}); // "1", undefined, undefined
lol.call({first: '1'}, '2'); // "1", "2", undefined
lol.call({first: '1'}, '2', '3'); // "1", "2", "3"
lol.apply({first: '1'}); // "1", undefined, undefined
lol.apply({first: '1'}, ['2', '3']); // "1", "2", "3"
const newLol = lol.bind({first: '1'});
newLol(); // "1", undefined, undefined
newLol('2'); // "1", "2", undefined
newLol('2', '3'); // "1", "2", "3"
const newOmg = lol.bind({first: '1'}, '2');
newOmg(); // "1", "2", undefined
newOmg('3'); // "1", "2", "3"
const newWtf = lol.bind({first: '1'}, '2', '3');
newWtf(); // "1", "2", "3"
Another usage is that you can pass binded function as an argument to another function which is operating under another execution context.
var name = "sample";
function sample(){
console.log(this.name);
}
var cb = sample.bind(this);
function somefunction(cb){
//other code
cb();
}
somefunction.call({}, cb);
In addition to what have been said, the bind() method allows an object to borrow a method from another object without making a copy of that method. This is known as function borrowing in JavaScript.
i did not read above code but i learn something in simple so want to share here about bind method after bind method we can use it as any normal method.
<pre> note: do not use arrow function it will show error undefined </pre>
let solarSystem = {
sun: 'red',
moon : 'white',
sunmoon : function(){
let dayNight = this.sun + ' is the sun color and present in day and '+this.moon + ' is the moon color and prenet in night';
return dayNight;
}
}
let work = function(work,sleep){
console.log(this.sunmoon()); // accessing the solatSystem it show error undefine sunmmon untill now because we can't access directly for that we use .bind()
console.log('i work in '+ work +' and sleep in '+sleep);
}
let outPut = work.bind(solarSystem);
outPut('day','night')
bind is a function which is available in java script prototype, as the name suggest bind is used to bind your function call to the context whichever you are dealing with for eg:
var rateOfInterest='4%';
var axisBank=
{
rateOfInterest:'10%',
getRateOfInterest:function()
{
return this.rateOfInterest;
}
}
axisBank.getRateOfInterest() //'10%'
let knowAxisBankInterest=axisBank.getRateOfInterest // when you want to assign the function call to a varaible we use this syntax
knowAxisBankInterest(); // you will get output as '4%' here by default the function is called wrt global context
let knowExactAxisBankInterest=knowAxisBankInterest.bind(axisBank); //so here we need bind function call to its local context
knowExactAxisBankInterest() // '10%'

Why pass an undefined javascript function parameter?

So I'm learning Javascript and I see this code:
var apple = {//... an object with some properties};
var fruit = apple.someMethod(function (b) {return b.a_property_of_apple});
Where someMethod and a_property_of_apple are valid methods and properties.
My question pertains to the argument, b, of the anonymous function which is not declared or defined anywhere else:
function (b) {return ...
What is going on here? What is b and why is it being used?
Apologies in advance for the basic nature of the question. If someone just wants to drop some focused terms on me to read up on that would be great short of an explanation.
The anonymous function is a callback function being passed to the apple.method() invocation.
apple.method() will invoke that anonymous function at some point during it's execution, ( or pass it to another function ). Whenever it's invoked it will be invoked with an argument that will be available inside the callback. You could call it b, or response, or whatever you want (logical names are best) and be able to use it within the anonymous function.
You should read about Callback functions over at MDN.
EDIT: I will explain the parts to you
var apple = {} This is the definition of an object
var fruit = apple.someMethod(function (b) {return b.a_property_of_apple}); is defining that fruit is equal to the return value of the invocation of apple.someMethod(...)
apple.someMethod(function (b) {return b.a_property_of_apple}); is the invocation of apple.someMethod with function (b) {return b.a_property_of_apple} as the only argument.
The b argument in the anonymous function function (b) {return b.a_property_of_apple} will be passed to it's invocation within the apple.someMethod.
Here is an example snippet.
// define apple
var apple = {
// define method
someMethod: function( callback ) {
var obj = {
a_property_of_apple: "Eat me!" // this will be returned
}
// return the invocation of callback with obj as argument
return callback(obj);
}
}
var fruit = apple.someMethod(function (b) {return b.a_property_of_apple});
console.log(fruit);
EDIT: Ok, going to use something slightly less abstract as an example.
// notice employees being passed to this function
// that is called an argument and is usable inside the function
var orginization = function( employees ) {
// this will take the empoyees argument and assign it to this.employees
// or set this.employees to an empty array if there is no employees argument
this.employees = employees || [ ];
// this is a method ( a method is a function on an object )
// this function takes 3 arguments
this.addEmployee = function( employee ) {
// we use the 3 arguments to push a new object with title, name, and salary
// properties provided by the function arguments
this.employees.push( employee );
}
// this method returns the value stored in this.employees
this.getEmployees = function() {
return this.employees;
}
}
// this is a variable an array of employees only containing 1 employee
// i will use it in the creation of my new orginization
var employess = [
{
title: "CEO",
name: "Enola",
salary: "$$$$$$$"
}
];
// i use the new to create learningInc from originization( employees )
// originization is a constructor function which creates an object
// with methods and properties found on the constructor
var learningInc = new orginization( employess );
// console.log learningInc.getEmployees() an you will see still only the CEO
// works here
console.log( "before newHire: ", learningInc.getEmployees() );
// lets make a newHire
var newHire = {
title: "Peon",
name: "Sadly McFrownFace",
salary: "$"
};
// add the newHire to the employess of learningInc wth out getEmployees() method
learningInc.addEmployee( newHire );
// log the new value of learningInc.getEmployees and you see we now have 2 employees
console.log( "after newHire: ", learningInc.getEmployees() );
Ok now notice this line var learningInc = new orginization( employess );
The employees variable I'm passing to this function as an argument is used in this function var orginization = function( employees ) { ... }.
Hope this help.
My question pertains to the parameter, b, of the anonymous function which is not declared or defined anywhere else: What is going on here?
What is b and why is it being used?
Why you say it is not declared? It is declared right there. Consider this simple JavaScript function:
function doSomething(a, b){
//do something here;
}
In this code, we are creating a function, naming it "doSomething", and declaring two parameters for it a and b. This is how we declare function parameters in JavaScript. Now your example:
function (b) {return ...
is exactly the same, except we didn't give this function a name, which means it is an anonymous function. That's the only difference, but its parameter b is declared right there like any standard function. So there is nothing special going here, it's a standard function parameter and used as such.
There are a couple concepts at work here
Function declarations vs function expressions; you can use function as an operator to define a function, and assign the function to an identifier and pass it around like any normal object
Callbacks; you can pass a function CB into another function A to be called by A (as defined by A)
Passing something without an identifier
Function Declaration
// declare function
function foo(argFoo) {
console.log('foo', argFoo);
}
// invoke function
foo('was declared'); // "foo" "was declared"
Function Expression
// express function
var bar = function (argBar) {
console.log('bar', argBar);
};
// invoke function
bar('was expressed'); // "bar" "was expressed"
Callbacks
function fizz(callback) {
console.log('first I fizz');
callback();
}
function buzz() {
console.log('then I buzz');
}
fizz(buzz);
// "first I fizz"
// "then I buzz"
Passing without an Identifier,
Basically, defining things in-place
// say we have some fn fizzbuzz
function fizzbuzz(foo) {
console.log(foo);
}
// we could pre-define what we want to pass to it
var i = 1;
fizzbuzz(i); // 1
// or we could pass directly
fizzbuzz(1); // 1
// with anything we like
fizzbuzz({some: 'object'}); // {some: "object"}
// even a function
fizzbuzz(function () {}); // function () {}
Maybe if I break down what is happening into more readable code, you can see what is happening.
someMethod is a method that take a function as an argument. This is more easily seen when broken down like below.
It's up to someMethod to determine what they do with that function. In this example, I am executing the function being passed into someMethod and passing it my this context.
var apple = {
name: 'Apple',
someMethod: function(func) {
return func(this);
}
};
function getName (b) {
return b.name;
};
const name = apple.someMethod(getName); // Apple
To your question: b is defined as the first argument to your anonymous function. This is more clearly expressed when the code is broken out above. But you could also express it like this:
const name = apple.someMethod(function(x) { return x.name; }); // Apple
or like this using ES6:
const name = apple.someMethod(x => x.name); // Apple

Bind more arguments of an already bound function in Javascript

I try to sort my thoughts about how javascript's bind() works.
I see that if I do
var f = function (a) { ... }
var g = f.bind(obj);
g(1)
then f is called with obj as this and 1 as a.
What I thought is g is a wrapper function around f.
But when I do
var f = function (a) { ... }
var g = f.bind(obj);
g.call(1)
then f is called with 1 as this and a undefined.
So it seems g is not just a simple wrapper, but call somehow differentiates between normal and bound functions.
One more thing is I cannot partially apply a function more times.
var f = function (a) { ... }
var g = f.bind(obj);
var h = g.bind(1);
h();
Then f is called with obj as this and a undefined.
What is the cause of this behavior?
Edit
The constructs in this question are actually wrong, see the accepted answer on what they should look like (in general I haven't noticed that call and bind do always need the context argument as the first argument).
Once you bound an object to a function with bind, you cannot override it. It's clearly written in the specs, as you can see in MDN documentation:
"The bind() function creates a new function (a bound function) with the same function body (internal call property in ECMAScript 5 terms) as the function it is being called on (the bound function's target function) with the this value bound to the first argument of bind(), which cannot be overridden."
That means, also if you do:
g.call(1);
You will get obj as this, and not 1 – on the browsers that follows the specs.
You can of course binds multiple arguments, so:
var sum = function(a, b, c) { return a + b + c };
var sumAB = sum.bind(null, 1, 5);
var sumC = sumAB.bind(null, 2);
console.log(sumC());
But the context object will be always the one specified with the first bind, because it cannot be overwritten.
Just to avoid confusion, the first argument of call is the context object (this), then you will have the rest of the argument.
It means:
var obj = { foo: function(bar) { console.log(bar) } };
obj.foo('hello');
// equivalent to:
var foo = obj.foo;
foo.call(obj, 'hello');
Hope it helps.
You never passed any arguments — you only ever set context. call's first argument is received as context (this), and arguments 2 onwards are received as the called function's arguments 1 and onwards. Meanwhile, bind creates a new function with a new context — arguments are passed when it's invoked.
Here are ways of passing 1 as function f's argument a following on from your first code block:
f( 1 );
g( 1 );
g.call( this, 1 );
g.apply( this, [ 1 ] );
Function.prototype.call()
With the call() method, you can write a method that can be used on different objects. In other words with call(), an object can use a method belonging to another object. More information
const person = {
fullName: function() {
return this.firstName + " " + this.lastName;
}
}
const person1 = {
firstName:"John",
lastName: "Doe"
}
const person2 = {
firstName:"Mary",
lastName: "Doe"
}
// This will return "John Doe":
console.log(person.fullName.call(person1));
The call() allows for a function/method belonging to one object to be assigned and called for a different object.
call() provides a new value of this to the function/method. With call(), you can write a method once and then inherit it in another object, without having to rewrite the method for the new object.
> Using call to chain constructors for an object
You can use call to chain constructors for an object (similar to Java).
In the following example, the constructor for the Product object is defined with two parameters: name and price.
Two other functions, Food and Toy, invoke Product, passing this, name, and price. Product initializes the properties name and price, both specialized functions define the category.
function Product(name, price) {
this.name = name;
this.price = price;
}
function Food(name, price) {
Product.call(this, name, price);
this.category = 'food';
}
function Toy(name, price) {
Product.call(this, name, price);
this.category = 'toy';
}
const cheese = new Food('feta', 5);
const fun = new Toy('robot', 40);
console.log(cheese);
console.log(fun);
> Using call to invoke an anonymous function
In this example, we create an anonymous function and use call to invoke it on every object in an array.
The main purpose of the anonymous function here is to add a print function to every object, which is able to print the correct index of the object in the array.
const animals = [
{ species: 'Lion', name: 'King' },
{ species: 'Whale', name: 'Fail' }
];
for (let i = 0; i < animals.length; i++) {
(function(i) {
this.print = function() {
console.log('#' + i + ' ' + this.species
+ ': ' + this.name);
}
this.print();
}).call(animals[i], i);
}
> Using call to invoke a function and specifying the context for 'this'
In the example below, when we call greet, the value of this will be bound to object obj.
function greet() {
const reply = [this.animal, 'typically sleep between', this.sleepDuration].join(' ');
console.log(reply);
}
const obj = {
animal: 'cats', sleepDuration: '12 and 16 hours'
};
greet.call(obj); // cats typically sleep between 12 and 16 hours
> Using call to invoke a function and without specifying the first argument
In the example below, we invoke the display function without passing the first argument. If the first argument is not passed, the value of this is bound to the global object.
var sData = 'Wisen';
function display() {
console.log('sData value is %s ', this.sData);
}
display.call(); // sData value is Wisen
Note: In strict mode, the value of this will be undefined. See below.
'use strict';
var sData = 'Wisen';
function display() {
console.log('sData value is %s ', this.sData);
}
display.call(); // Cannot read the property of 'sData' of undefined
For more read you can visit reference
Function.prototype.bind()
The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.
const module = {
x: 42,
getX: function() {
return this.x;
}
};
const unboundGetX = module.getX;
console.log(unboundGetX()); // The function gets invoked at the global scope
// expected output: undefined
const boundGetX = unboundGetX.bind(module);
console.log(boundGetX());
// expected output: 42
> Creating a bound function
The simplest use of bind() is to make a function that, no matter how it is called, is called with a particular this value.
A common mistake for new JavaScript programmers is to extract a method from an object, then to later call that function and expect it to use the original object as its this (e.g., by using the method in callback-based code).
Without special care, however, the original object is usually lost. Creating a bound function from the function, using the original object, neatly solves this problem:
this.x = 9; // 'this' refers to global 'window' object here in a browser
const module = {
x: 81,
getX: function() { return this.x; }
};
module.getX();
// returns 81
const retrieveX = module.getX;
retrieveX();
// returns 9; the function gets invoked at the global scope
// Create a new function with 'this' bound to module
// New programmers might confuse the
// global variable 'x' with module's property 'x'
const boundGetX = retrieveX.bind(module);
console.log(boundGetX());
// returns 81
> Partially applied functions
The next simplest use of bind() is to make a function with pre-specified initial arguments.
These arguments (if any) follow the provided this value and are then inserted at the start of the arguments passed to the target function, followed by whatever arguments are passed to the bound function at the time it is called.
function list() {
return Array.prototype.slice.call(arguments);
}
function addArguments(arg1, arg2) {
return arg1 + arg2;
}
const list1 = list(1, 2, 3);
// [1, 2, 3]
const result1 = addArguments(1, 2);
// 3
// Create a function with a preset leading argument
const leadingThirtysevenList = list.bind(null, 37);
// Create a function with a preset first argument.
const addThirtySeven = addArguments.bind(null, 37);
const list2 = leadingThirtysevenList();
// [37]
const list3 = leadingThirtysevenList(1, 2, 3);
// [37, 1, 2, 3]
const result2 = addThirtySeven(5);
// 37 + 5 = 42
const result3 = addThirtySeven(5, 10);
// 37 + 5 = 42
// (the second argument is ignored)
> With setTimeout()
By default within setTimeout(), the this keyword will be set to the window (or global) object. When working with class methods that require this to refer to class instances, you may explicitly bind this to the callback function, in order to maintain the instance.
function LateBloomer() {
this.petalCount = Math.floor(Math.random() * 12) + 1;
}
// Declare bloom after a delay of 1 second
LateBloomer.prototype.bloom = function() {
window.setTimeout(this.declare.bind(this), 1000);
};
LateBloomer.prototype.declare = function() {
console.log(`I am a beautiful flower with ${this.petalCount} petals!`);
};
const flower = new LateBloomer();
flower.bloom();
// after 1 second, calls 'flower.declare()'
And if you want to know more about bind method, read this resource

Javascript call() & apply() vs bind()?

I already know that apply and call are similar functions which set this (context of a function).
The difference is with the way we send the arguments (manual vs array)
Question:
But when should I use the bind() method ?
var obj = {
x: 81,
getX: function() {
return this.x;
}
};
alert(obj.getX.bind(obj)());
alert(obj.getX.call(obj));
alert(obj.getX.apply(obj));
jsbin
Use .bind() when you want that function to later be called with a certain context, useful in events. Use .call() or .apply() when you want to invoke the function immediately, and modify the context.
Call/apply call the function immediately, whereas bind returns a function that, when later executed, will have the correct context set for calling the original function. This way you can maintain context in async callbacks and events.
I do this a lot:
function MyObject(element) {
this.elm = element;
element.addEventListener('click', this.onClick.bind(this), false);
};
MyObject.prototype.onClick = function(e) {
var t=this; //do something with [t]...
//without bind the context of this function wouldn't be a MyObject
//instance as you would normally expect.
};
I use it extensively in Node.js for async callbacks that I want to pass a member method for, but still want the context to be the instance that started the async action.
A simple, naive implementation of bind would be like:
Function.prototype.bind = function(ctx) {
var fn = this;
return function() {
fn.apply(ctx, arguments);
};
};
There is more to it (like passing other args), but you can read more about it and see the real implementation on the MDN.
They all attach this into function (or object) and the difference is in the function invocation (see below).
call attaches this into function and executes the function immediately:
var person = {
name: "James Smith",
hello: function(thing) {
console.log(this.name + " says hello " + thing);
}
}
person.hello("world"); // output: "James Smith says hello world"
person.hello.call({ name: "Jim Smith" }, "world"); // output: "Jim Smith says hello world"
bind attaches this into function and it needs to be invoked separately like this:
var person = {
name: "James Smith",
hello: function(thing) {
console.log(this.name + " says hello " + thing);
}
}
person.hello("world"); // output: "James Smith says hello world"
var helloFunc = person.hello.bind({ name: "Jim Smith" });
helloFunc("world"); // output: Jim Smith says hello world"
or like this:
...
var helloFunc = person.hello.bind({ name: "Jim Smith" }, "world");
helloFunc(); // output: Jim Smith says hello world"
apply is similar to call except that it takes an array-like object instead of listing the arguments out one at a time:
function personContainer() {
var person = {
name: "James Smith",
hello: function() {
console.log(this.name + " says hello " + arguments[1]);
}
}
person.hello.apply(person, arguments);
}
personContainer("world", "mars"); // output: "James Smith says hello mars", note: arguments[0] = "world" , arguments[1] = "mars"
Answer in SIMPLEST form
Call invokes the function and allows you to pass in arguments one by
one.
Apply invokes the function and allows you to pass in arguments
as an array.
Bind returns a new function, allowing you to pass in a
this array and any number of arguments.
Apply vs. Call vs. Bind Examples
Call
var person1 = {firstName: 'Jon', lastName: 'Kuperman'};
var person2 = {firstName: 'Kelly', lastName: 'King'};
function say(greeting) {
console.log(greeting + ' ' + this.firstName + ' ' + this.lastName);
}
say.call(person1, 'Hello'); // Hello Jon Kuperman
say.call(person2, 'Hello'); // Hello Kelly King
Apply
var person1 = {firstName: 'Jon', lastName: 'Kuperman'};
var person2 = {firstName: 'Kelly', lastName: 'King'};
function say(greeting) {
console.log(greeting + ' ' + this.firstName + ' ' + this.lastName);
}
say.apply(person1, ['Hello']); // Hello Jon Kuperman
say.apply(person2, ['Hello']); // Hello Kelly King
Bind
var person1 = {firstName: 'Jon', lastName: 'Kuperman'};
var person2 = {firstName: 'Kelly', lastName: 'King'};
function say() {
console.log('Hello ' + this.firstName + ' ' + this.lastName);
}
var sayHelloJon = say.bind(person1);
var sayHelloKelly = say.bind(person2);
sayHelloJon(); // Hello Jon Kuperman
sayHelloKelly(); // Hello Kelly King
When To Use Each
Call and apply are pretty interchangeable. Just decide whether it’s easier to send in an array or a comma separated list of arguments.
I always remember which one is which by remembering that Call is for comma (separated list) and Apply is for Array.
Bind is a bit different. It returns a new function. Call and Apply execute the current function immediately.
Bind is great for a lot of things. We can use it to curry functions like in the above example. We can take a simple hello function and turn it into a helloJon or helloKelly. We can also use it for events like onClick where we don’t know when they’ll be fired but we know what context we want them to have.
Reference: codeplanet.io
I created this comparison between function objects, function calls, call/apply and bind a while ago:
.bind allows you to set the this value now while allowing you to execute the function in the future, because it returns a new function object.
TL;DR:
In simple words, bind creates the function, call and apply executes the function whereas apply expects the parameters in array
Full Explanation
Assume we have multiplication function
function multiplication(a,b){
console.log(a*b);
}
Lets create some standard functions using bind
var multiby2 = multiplication.bind(this,2);
Now multiby2(b) is equal to multiplication(2,b);
multiby2(3); //6
multiby2(4); //8
What if I pass both the parameters in bind
var getSixAlways = multiplication.bind(this,3,2);
Now getSixAlways() is equal to multiplication(3,2);
getSixAlways();//6
even passing parameter returns 6;
getSixAlways(12); //6
var magicMultiplication = multiplication.bind(this);
This create a new multiplication function and assigns it to magicMultiplication.
Oh no, we are hiding the multiplication functionality into magicMultiplication.
calling
magicMultiplication returns a blank function b()
on execution it works fine
magicMultiplication(6,5); //30
How about call and apply?
magicMultiplication.call(this,3,2); //6
magicMultiplication.apply(this,[5,2]); //10
It allows to set the value for this independent of how the function is called. This is very useful when working with callbacks:
function sayHello(){
alert(this.message);
}
var obj = {
message : "hello"
};
setTimeout(sayHello.bind(obj), 1000);
To achieve the same result with call would look like this:
function sayHello(){
alert(this.message);
}
var obj = {
message : "hello"
};
setTimeout(function(){sayHello.call(obj)}, 1000);
The main concept behind all this methods is Function burrowing.
Function borrowing allows us to use the methods of one object on a different object without having to make a copy of that method and maintain it in two separate places. It is accomplished through the use of . call() , . apply() , or . bind() , all of which exist to explicitly set this on the method we are borrowing
Call invokes the function immediately and allows you to pass in arguments one by
one
Apply invokes the function immediately and allows you to pass in arguments
as an array.
Bind returns a new function, and you can invoke/call it anytime you want by invoking a function.
Below is an example of all this methods
let name = {
firstname : "Arham",
lastname : "Chowdhury",
}
printFullName = function(hometown,company){
console.log(this.firstname + " " + this.lastname +", " + hometown + ", " + company)
}
CALL
the first argument e.g name inside call method is always a reference
to (this) variable and latter will be function variable
printFullName.call(name,"Mumbai","Taufa"); //Arham Chowdhury, Mumbai, Taufa
APPLY
apply method is same as the call method
the only diff is that, the function arguments are passed in Array list
printFullName.apply(name, ["Mumbai","Taufa"]); //Arham Chowdhury, Mumbai, Taufa
BIND
bind method is same as call except that ,the bind returns a function that can be used later by invoking it (does'nt call it immediately)
let printMyNAme = printFullName.bind(name,"Mumbai","Taufa");
printMyNAme(); //Arham Chowdhury, Mumbai, Taufa
printMyNAme() is the function which invokes the function
below is the link for jsfiddle
https://codepen.io/Arham11/pen/vYNqExp
Both Function.prototype.call() and Function.prototype.apply() call a function with a given this value, and return the return value of that function.
Function.prototype.bind(), on the other hand, creates a new function with a given this value, and returns that function without executing it.
So, let's take a function that looks like this :
var logProp = function(prop) {
console.log(this[prop]);
};
Now, let's take an object that looks like this :
var Obj = {
x : 5,
y : 10
};
We can bind our function to our object like this :
Obj.log = logProp.bind(Obj);
Now, we can run Obj.log anywhere in our code :
Obj.log('x'); // Output : 5
Obj.log('y'); // Output : 10
Where it really gets interesting, is when you not only bind a value for this, but also for for its argument prop :
Obj.logX = logProp.bind(Obj, 'x');
Obj.logY = logProp.bind(Obj, 'y');
We can now do this :
Obj.logX(); // Output : 5
Obj.logY(); // Output : 10
bind: It binds the function with provided value and context but it does not executes the function. To execute function you need to call the function.
call: It executes the function with provided context and parameter.
apply: It executes the function with provided context and
parameter as array.
Here is one good article to illustrate the difference among bind(), apply() and call(), summarize it as below.
bind() allows us to easily set which specific object will be bound to this when a function or method is invoked.
// This data variable is a global variable​
var data = [
{name:"Samantha", age:12},
{name:"Alexis", age:14}
]
var user = {
// local data variable​
data :[
{name:"T. Woods", age:37},
{name:"P. Mickelson", age:43}
],
showData:function (event) {
var randomNum = ((Math.random () * 2 | 0) + 1) - 1; // random number between 0 and 1​
console.log (this.data[randomNum].name + " " + this.data[randomNum].age);
}
}
// Assign the showData method of the user object to a variable​
var showDataVar = user.showData;
showDataVar (); // Samantha 12 (from the global data array, not from the local data array)​
/*
This happens because showDataVar () is executed as a global function and use of this inside
showDataVar () is bound to the global scope, which is the window object in browsers.
*/
// Bind the showData method to the user object​
var showDataVar = user.showData.bind (user);
// Now the we get the value from the user object because the this keyword is bound to the user object​
showDataVar (); // P. Mickelson 43​
bind() allow us to borrow methods
// Here we have a cars object that does not have a method to print its data to the console​
var cars = {
data:[
{name:"Honda Accord", age:14},
{name:"Tesla Model S", age:2}
]
}
// We can borrow the showData () method from the user object we defined in the last example.​
// Here we bind the user.showData method to the cars object we just created.​
cars.showData = user.showData.bind (cars);
cars.showData (); // Honda Accord 14​
One problem with this example is that we are adding a new method showData on the cars object and
we might not want to do that just to borrow a method because the cars object might already have a property or method name showData.
We don’t want to overwrite it accidentally. As we will see in our discussion of Apply and Call below,
it is best to borrow a method using either the Apply or Call method.
bind() allow us to curry a function
Function Currying, also known as partial function application, is the use of a
function (that accept one or more arguments) that returns a new function with some of the arguments already set.
function greet (gender, age, name) {
// if a male, use Mr., else use Ms.​
var salutation = gender === "male" ? "Mr. " : "Ms. ";
if (age > 25) {
return "Hello, " + salutation + name + ".";
}else {
return "Hey, " + name + ".";
}
}
We can use bind() to curry this greet function
// So we are passing null because we are not using the "this" keyword in our greet function.
var greetAnAdultMale = greet.bind (null, "male", 45);
greetAnAdultMale ("John Hartlove"); // "Hello, Mr. John Hartlove."
var greetAYoungster = greet.bind (null, "", 16);
greetAYoungster ("Alex"); // "Hey, Alex."​
greetAYoungster ("Emma Waterloo"); // "Hey, Emma Waterloo."
apply() or call() to set this value
The apply, call, and bind methods are all used to set the this value when invoking a method, and they do it in slightly
different ways to allow use direct control and versatility in our JavaScript code.
The apply and call methods are almost identical when setting the this value except that you pass the function parameters to apply () as an array, while you have to list the parameters individually to pass them to the call () method.
Here is one example to use call or apply to set this in the callback function.
// Define an object with some properties and a method​
// We will later pass the method as a callback function to another function​
var clientData = {
id: 094545,
fullName: "Not Set",
// setUserName is a method on the clientData object​
setUserName: function (firstName, lastName) {
// this refers to the fullName property in this object​
this.fullName = firstName + " " + lastName;
}
};
function getUserInput (firstName, lastName, callback, callbackObj) {
// The use of the Apply method below will set the "this" value to callbackObj​
callback.apply (callbackObj, [firstName, lastName]);
}
// The clientData object will be used by the Apply method to set the "this" value​
getUserInput ("Barack", "Obama", clientData.setUserName, clientData);
// the fullName property on the clientData was correctly set​
console.log (clientData.fullName); // Barack Obama
Borrow functions with apply or call
Borrow Array methods
Let’s create an array-like object and borrow some array methods to operate on the our array-like object.
// An array-like object: note the non-negative integers used as keys​
var anArrayLikeObj = {0:"Martin", 1:78, 2:67, 3:["Letta", "Marieta", "Pauline"], length:4 };
// Make a quick copy and save the results in a real array:
// First parameter sets the "this" value​
var newArray = Array.prototype.slice.call (anArrayLikeObj, 0);
console.log (newArray); // ["Martin", 78, 67, Array[3]]​
// Search for "Martin" in the array-like object​
console.log (Array.prototype.indexOf.call (anArrayLikeObj, "Martin") === -1 ? false : true); // true​
Another common case is that convert arguments to array as following
// We do not define the function with any parameters, yet we can get all the arguments passed to it​
function doSomething () {
var args = Array.prototype.slice.call (arguments);
console.log (args);
}
doSomething ("Water", "Salt", "Glue"); // ["Water", "Salt", "Glue"]
Borrow other methods
var gameController = {
scores :[20, 34, 55, 46, 77],
avgScore:null,
players :[
{name:"Tommy", playerID:987, age:23},
{name:"Pau", playerID:87, age:33}
]
}
var appController = {
scores :[900, 845, 809, 950],
avgScore:null,
avg :function () {
var sumOfScores = this.scores.reduce (function (prev, cur, index, array) {
return prev + cur;
});
this.avgScore = sumOfScores / this.scores.length;
}
}
// Note that we are using the apply () method, so the 2nd argument has to be an array​
appController.avg.apply (gameController);
console.log (gameController.avgScore); // 46.4​
// appController.avgScore is still null; it was not updated, only gameController.avgScore was updated​
console.log (appController.avgScore); // null​
Use apply() to execute variable-arity function
The Math.max is one example of variable-arity function,
// We can pass any number of arguments to the Math.max () method​
console.log (Math.max (23, 11, 34, 56)); // 56
But what if we have an array of numbers to pass to Math.max? We cannot do this:
var allNumbers = [23, 11, 34, 56];
// We cannot pass an array of numbers to the the Math.max method like this​
console.log (Math.max (allNumbers)); // NaN
This is where the apply () method helps us execute variadic functions. Instead of the above, we have to pass the array of numbers using apply () thus:
var allNumbers = [23, 11, 34, 56];
// Using the apply () method, we can pass the array of numbers:
console.log (Math.max.apply (null, allNumbers)); // 56
The basic difference between Call, Apply and Bind are:
Bind will be used if you want your execution context to come later in the picture.
Ex:
var car = {
registrationNumber: "007",
brand: "Mercedes",
displayDetails: function(ownerName){
console.log(ownerName + ' this is your car ' + '' + this.registrationNumber + " " + this.brand);
}
}
car.displayDetails('Nishant'); // **Nishant this is your car 007 Mercedes**
Let's say i want use this method in some other variable
var car1 = car.displayDetails('Nishant');
car1(); // undefined
To use the reference of car in some other variable you should use
var car1 = car.displayDetails.bind(car, 'Nishant');
car1(); // Nishant this is your car 007 Mercedes
Let's talk about more extensive use of bind function
var func = function() {
console.log(this)
}.bind(1);
func();
// Number: 1
Why? Because now func is bind with Number 1, if we don't use bind in that case it will point to Global Object.
var func = function() {
console.log(this)
}.bind({});
func();
// Object
Call, Apply are used when you want to execute the statement at the same time.
var Name = {
work: "SSE",
age: "25"
}
function displayDetails(ownerName) {
console.log(ownerName + ", this is your name: " + 'age' + this.age + " " + 'work' + this.work);
}
displayDetails.call(Name, 'Nishant')
// Nishant, this is your name: age25 workSSE
// In apply we pass an array of arguments
displayDetails.apply(Name, ['Nishant'])
// Nishant, this is your name: age25 workSSE
call/apply executes function immediately:
func.call(context, arguments);
func.apply(context, [argument1,argument2,..]);
bind doesn't execute function immediately, but returns wrapped apply function (for later execution):
function bind(func, context) {
return function() {
return func.apply(context, arguments);
};
}
Call apply and bind. and how they are different.
Lets learn call and apply using any daily terminology.
You have three automobiles your_scooter , your_car and your_jet which start with the same mechanism (method).
We created an object automobile with a method push_button_engineStart.
var your_scooter, your_car, your_jet;
var automobile = {
push_button_engineStart: function (runtime){
console.log(this.name + "'s" + ' engine_started, buckle up for the ride for ' + runtime + " minutes");
}
}
Lets understand when is call and apply used. Lets suppose that you are an engineer and you have your_scooter, your_car and your_jet which did not come with a push_button_engine_start and you wish to use a third party push_button_engineStart.
If you run the following lines of code, they will give an error. WHY?
//your_scooter.push_button_engineStart();
//your_car.push_button_engineStart();
//your_jet.push_button_engineStart();
automobile.push_button_engineStart.apply(your_scooter,[20]);
automobile.push_button_engineStart.call(your_jet,10);
automobile.push_button_engineStart.call(your_car,40);
So the above example is successfully gives your_scooter, your_car, your_jet a feature from automobile object.
Let's dive deeper
Here we will split the above line of code.
automobile.push_button_engineStart is helping us to get the method being used.
Further we use apply or call using the dot notation.
automobile.push_button_engineStart.apply()
Now apply and call accept two parameters.
context
arguments
So here we set the context in the final line of code.
automobile.push_button_engineStart.apply(your_scooter,[20])
Difference between call and apply is just that apply accepts parameters in the form of an array while call simply can accept a comma separated list of arguments.
what is JS Bind function?
A bind function is basically which binds the context of something and then stores it into a variable for execution at a later stage.
Let's make our previous example even better. Earlier we used a method belonging to the automobile object and used it to equip your_car, your_jet and your_scooter. Now lets imagine we want to give a separate push_button_engineStart separately to start our automobiles individually at any later stage of the execution we wish.
var scooty_engineStart = automobile.push_button_engineStart.bind(your_scooter);
var car_engineStart = automobile.push_button_engineStart.bind(your_car);
var jet_engineStart = automobile.push_button_engineStart.bind(your_jet);
setTimeout(scooty_engineStart,5000,30);
setTimeout(car_engineStart,10000,40);
setTimeout(jet_engineStart,15000,5);
still not satisfied?
Let's make it clear as teardrop. Time to experiment. We will go back to call and apply function application and try storing the value of the function as a reference.
The experiment below fails because call and apply are invoked immediately, hence, we never get to the stage of storing a reference in a variable which is where bind function steals the show
var test_function = automobile.push_button_engineStart.apply(your_scooter);
Syntax
call(thisArg, arg1, arg2, ...)
apply(thisArg, argsArray)
bind(thisArg[, arg1[, arg2[, ...]]])
Here
thisArg is the object
argArray is an array object
arg1, arg2, arg3,... are additional arguments
function printBye(message1, message2){
console.log(message1 + " " + this.name + " "+ message2);
}
var par01 = { name:"John" };
var msgArray = ["Bye", "Never come again..."];
printBye.call(par01, "Bye", "Never come again...");
//Bye John Never come again...
printBye.call(par01, msgArray);
//Bye,Never come again... John undefined
//so call() doesn't work with array and better with comma seperated parameters
//printBye.apply(par01, "Bye", "Never come again...");//Error
printBye.apply(par01, msgArray);
//Bye John Never come again...
var func1 = printBye.bind(par01, "Bye", "Never come again...");
func1();//Bye John Never come again...
var func2 = printBye.bind(par01, msgArray);
func2();//Bye,Never come again... John undefined
//so bind() doesn't work with array and better with comma seperated parameters
JavaScript Call()
const person = {
name: "Lokamn",
dob: 12,
print: function (value,value2) {
console.log(this.dob+value+value2)
}
}
const anotherPerson= {
name: "Pappu",
dob: 12,
}
person.print.call(anotherPerson,1,2)
JavaScript apply()
name: "Lokamn",
dob: 12,
print: function (value,value2) {
console.log(this.dob+value+value2)
}
}
const anotherPerson= {
name: "Pappu",
dob: 12,
}
person.print.apply(anotherPerson,[1,2])
**call and apply function are difference call take separate argument but apply take array
like:[1,2,3]
**
JavaScript bind()
name: "Lokamn",
dob: 12,
anotherPerson: {
name: "Pappu",
dob: 12,
print2: function () {
console.log(this)
}
}
}
var bindFunction = person.anotherPerson.print2.bind(person)
bindFunction()
Call: call invokes the function and allows you to pass arguments one by one
Apply: Apply invokes the function and allows you to pass arguments as an array
Bind: Bind returns a new function, allowing you to pass in a this array and any number of arguments.
var person1 = {firstName: 'Raju', lastName: 'king'};
var person2 = {firstName: 'chandu', lastName: 'shekar'};
function greet(greeting) {
console.log(greeting + ' ' + this.firstName + ' ' + this.lastName);
}
function greet2(greeting) {
console.log( 'Hello ' + this.firstName + ' ' + this.lastName);
}
greet.call(person1, 'Hello'); // Hello Raju king
greet.call(person2, 'Hello'); // Hello chandu shekar
greet.apply(person1, ['Hello']); // Hello Raju king
greet.apply(person2, ['Hello']); // Hello chandu shekar
var greetRaju = greet2.bind(person1);
var greetChandu = greet2.bind(person2);
greetRaju(); // Hello Raju king
greetChandu(); // Hello chandu shekar
call() :-- Here we pass the function arguments individually, not in an array format
var obj = {name: "Raushan"};
var greeting = function(a,b,c) {
return "Welcome "+ this.name + " to "+ a + " " + b + " in " + c;
};
console.log(greeting.call(obj, "USA", "INDIA", "ASIA"));
apply() :-- Here we pass the function arguments in an array format
var obj = {name: "Raushan"};
var cal = function(a,b,c) {
return this.name +" you got " + a+b+c;
};
var arr =[1,2,3]; // array format for function arguments
console.log(cal.apply(obj, arr));
bind() :--
var obj = {name: "Raushan"};
var cal = function(a,b,c) {
return this.name +" you got " + a+b+c;
};
var calc = cal.bind(obj);
console.log(calc(2,3,4));
Imagine, bind is not available.
you can easily construct it as follow :
var someFunction=...
var objToBind=....
var bindHelper = function (someFunction, objToBind) {
return function() {
someFunction.apply( objToBind, arguments );
};
}
bindHelper(arguments);
function sayHello() {
//alert(this.message);
return this.message;
}
var obj = {
message: "Hello"
};
function x(country) {
var z = sayHello.bind(obj);
setTimeout(y = function(w) {
//'this' reference not lost
return z() + ' ' + country + ' ' + w;
}, 1000);
return y;
}
var t = x('India')('World');
document.getElementById("demo").innerHTML = t;
Use bind for future calls to the function. Both apply and call invoke the function.
bind() also allows for additional arguments to be perpended to the args array.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind
In simple terms, all methods are used to set the context(this) explicitly in the regular function
Call: call invokes the function on given context and allows to pass arguments one by one
Apply: apply invokes the function on given context and allows to pass arguments as an array
Bind: bind returns a new function by setting the provided context, and allows to pass arguments one by one
Notes:
Call and Apply both are similar only difference is the way they expect arguments
The mentioned methods do not work with arrow function
The first difference between call(), apply(), and bind() methods in JavaScript is their time of execution!
call() and apply() being similar are executed instantly, whereas, bind() creates a new function which we have to explicitly call at any later point of time!
Another difference is, that while passing arguments, call() allows us to pass one by one separated by commas, apply() allows us to pass as an array of arguments, and bind() allows us to do both!
I have attached the example code below!
const person = {
fullName : function (randomMessage) {
return `Hello, ${this.firstName} ${this.lastName} ${randomMessage}`;
}
}
const personOne = {
firstName : "John",
lastName : "Doe"
}
const personTwo = {
firstName : "Jack",
lastName : "Adhikari"
}
let fullNameBind = person.fullName.bind(personOne, "--Binding");
let fullNameCall = person.fullName.call({firstName : "Sarah", lastName: "Holmes"}, "--Calling");
let fullNameApply = person.fullName.apply(personTwo, ["--Applying"]);
console.log(fullNameBind());
console.log(fullNameCall);
console.log(fullNameApply);
I think the same places of them are: all of them can change the this value of a function.The differences of them are: the bind function will return a new function as a result; the call and apply methods will execute the function immediately, but apply can accept a array as params,and it will parse the array separated.And also, the bind function can be Currying.
bind function should be use when we want to assign a function with particular context for eg.
var demo = {
getValue : function(){
console.log('demo object get value function')
}
setValue : function(){
setTimeout(this.getValue.bind(this),1000)
}
}
in above example if we call demo.setValue() function and pass this.getValue function directly then it doesn't call demo.setValue function directly because this in setTimeout refers to window object so we need to pass demo object context to this.getValue function using bind. it means we only passing function with the context of demo object not actully calling function.
Hope u understand .
for more information please refer
javascript bind function know in detail

The reason to use JS .call() method?

I'm interested what's the reason to have call() method in JS. It seems it duplicates usual method of calling this.
For example, I have a code with call().
var obj = {
objType: "Dog"
}
f = function(did_what, what) {
alert(this.objType + " " + did_what + " " + what);
}
f.call(obj, "ate", "food");
The output is "Dog ate food". But the same result I can get assigning the function to the object.
var obj = {
objType: "Dog"
}
f = function(did_what, what) {
alert(this.objType + " " + did_what + " " + what);
}
obj.a = f;
obj.a("ate", "food");
The result is the same. But this way is more understandable and convenient to use. Why call() is needed?
call is used when you want to control the scope that will be used in the function called. You might want the this keyword to be something else than the scope you assigned the function to, in those cases you can use call or apply to call the function with your own scope.
F.ex, it also allows you to call utility methods outside the scope, like when using "private" functions:
var obj = (function() {
var privateFn = function() {
alert(this.id);
}
return {
id: 123,
publicFn: function() {
privateFn.call(this);
}
};
}());
obj.publicFn();
In the example above, privateFn is not exposed in obj but it can still be constructed as if it was a part of the public scope (using this in the same way).
2017 Update
All functions by way of Function.prototype have the .call method. The reason to use .call() is to specify what the variable "this" refers to.
MDN specifies:
The call() method calls a function with a given this value and
arguments provided individually.
Consider the following:
function x() {
return this;
}
x()
In strict mode x() returns undefined in non strict mode it returns the Global object, Window in a browser context.
Example with .call() we tell it what "this" refers to:
function x() {
return this;
}
var obj = {
myName : 'Robert',
myLocation : 'Earth'
}
x.call(obj);
Result: {myName: "Robert", myLocation: "Earth"}. In the above example we are specifying the obj object as the value of this inside the function x()
It can be used to emulate inheritance in OOP.
Example:
var Robert = {
name: "Robert Rocha",
age: 12,
height: "5,1",
sex: "male",
describe: function() {
return "This is me " + this.name + " " + this.age + " " + this.height + " " + this.sex;
}
};
Lets say that the above is a master object(prototype) and you want to inherit the function describe in another object:
var Richard = {
name: "Richard Sash",
age: 25,
height: "6,4",
sex: "male",
}
The Richard object does not have the describe function and you want to simply inherit ,so to speak, the function. You would do it like so:
console.log( Robert.describe.call( Richard ) );
Output: This is me Richard Sash 25 6,4 male
You would probably use the second way in your example, but sometimes you want to use one object's functions on another object. An example would be using Array methods on Array-like objects like NodeLists
var el = document.getElementById("foo");
[].forEach.call(el.children, function(child, index) {
//Iterate over an element's children, performing an action on each one
});
It's to do with the concept of a first class function. Basically languages like Javascript allow you to treat functions as things their own right. Functions can be stored in variables or passed to other functions.
call() provides a way to execute a free standing function not attached to any other object.
After I read this , I understand why.
A common mistake for new JavaScript programmers is to extract a method from an object, then to later call that function and expect it to use the original object as its this (e.g., by using the method in callback-based code).
Without special care, however, the original object is usually lost. Creating a bound function from the function, using the original object, neatly solves this problem:
this.x = 9; // 'this' refers to global 'window' object here in a browser
const module = {
x: 81,
getX: function() { return this.x; }
};
module.getX();
// returns 81
const retrieveX = module.getX;
retrieveX();
// returns 9; the function gets invoked at the global scope
// Create a new function with 'this' bound to module
// New programmers might confuse the
// global variable 'x' with module's property 'x'
const boundGetX = retrieveX.bind(module);
boundGetX();
// returns 81
The origin is here

Categories