Related
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
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
With respect to JS, what's the difference between the two? I know methods are associated with objects, but am confused what's the purpose of functions? How does the syntax of each of them differ?
Also, what's the difference between these 2 syntax'es:
var myFirstFunc = function(param) {
//Do something
};
and
function myFirstFunc(param) {
//Do something
};
Also, I saw somewhere that we need to do something like this before using a function:
obj.myFirstFunc = myFirstFunc;
obj.myFirstFunc("param");
Why is the first line required, and what does it do?
Sorry if these are basic questions, but I'm starting with JS and am confused.
EDIT: For the last bit of code, this is what I'm talking about:
// here we define our method using "this", before we even introduce bob
var setAge = function (newAge) {
this.age = newAge;
};
// now we make bob
var bob = new Object();
bob.age = 30;
// and down here we just use the method we already made
bob.setAge = setAge;
To answer your title question as to what is the difference between a 'function' and a 'method'.
It's semantics and has to do with what you are trying to express.
In JavaScript every function is an object. An object is a collection of key:value pairs. If a value is a primitive (number, string, boolean), or another object, the value is considered a property. If a value is a function, it is called a 'method'.
Within the scope of an object, a function is referred to as a method of that object. It is invoked from the object namespace MyObj.theMethod(). Since we said that a function is an object, a function within a function can be considered a method of that function.
You could say things like “I am going to use the save method of my object.” And "This save method accepts a function as a parameter.” But you generally wouldn't say that a function accepts a method as a parameter.
Btw, the book JavaScript Patterns by Stoyan Stefanov covers your questions in detail, and I highly recommend it if you really want to understand the language. Here's a quote from the book on this subject:
So it could happen that a function A, being an object, has properties and methods, one of which happens to be another function B. Then B can accept a function C as an argument and, when executed, can return another function D.
There is a slight difference -
Method : Method is a function when object is associated with it.
var obj = {
name : "John snow",
work : function someFun(paramA, paramB) {
// some code..
}
Function : When no object is associated with it , it comes to function.
function fun(param1, param2){
// some code...
}
Many answers are saying something along the lines that a method is what a function is called when it is defined on an object.
While this is often true in the way the word is used when people talk about JavaScript or object oriented programming in general (see here), it is worth noting that in ES6 the term method has taken on a very specific meaning (see section 14.3 Method Definitions of the specs).
Method Definitions
A method (in the strict sense) is a function that was defined through the concise method syntax in an object literal or as a class method in a class declaration / expression:
// In object literals:
const obj = {
method() {}
};
// In class declarations:
class MyClass {
method() {}
}
Method Specificities
This answer gives a good overview about the specificities of methods (in the strict sense), namely:
methods get assigned an internal [[HomeObject]] property which allows them to use super.
methods are not created with a prototype property and they don't have an internal [[Construct]] method which means that they cannot be called with new.
the name of a method does not become a binding in the method's scope.
Below are some examples illustrating how methods (in the strict sense) differ from functions defined on objects through function expressions:
Example 1
const obj = {
method() {
super.test; // All good!
},
ordinaryFunction: function ordinaryFunction() {
super.test; // SyntaxError: 'super' keyword unexpected here
}
};
Example 2
const obj = {
method() {},
ordinaryFunction: function ordinaryFunction() {}
};
console.log( obj.ordinaryFunction.hasOwnProperty( 'prototype' ) ); // true
console.log( obj.method.hasOwnProperty( 'prototype' ) ); // false
new obj.ordinaryFunction(); // All good !
new obj.method(); // TypeError: obj.method is not a constructor
Example 3
const obj = {
method() {
console.log( method );
},
ordinaryFunction: function ordinaryFunction() {
console.log( ordinaryFunction );
}
};
obj.ordinaryFunction() // All good!
obj.method() // ReferenceError: method is not defined
A method is a property of an object whose value is a function. Methods are called on objects in the following format: object.method().
//this is an object named developer
const developer = {
name: 'Andrew',
sayHello: function () {
console.log('Hi there!');
},
favoriteLanguage: function (language) {
console.log(`My favorite programming language is ${language}`);
}
};
// favoriteLanguage: and sayHello: and name: all of them are proprieties in the object named developer
now lets say you needed to call favoriteLanguage propriety witch is a function inside the object..
you call it this way
developer.favoriteLanguage('JavaScript');
// My favorite programming language is JavaScript'
so what we name this: developer.favoriteLanguage('JavaScript');
its not a function its not an object? what it is? its a method
Your first line, is creating an object that references a function. You would reference it like this:
myFirstFunc(param);
But you can pass it to another function since it will return the function like so:
function mySecondFunction(func_param){}
mySecondFunction(myFirstFunc);
The second line just creates a function called myFirstFunc which would be referenced like this:
myFirstFunc(param);
And is limited in scope depending on where it is declared, if it is declared outside of any other function it belongs to the global scope. However you can declare a function inside another function. The scope of that function is then limited to the function its declared inside of.
function functionOne(){
function functionTwo(){}; //only accessed via the functionOne scope!
}
Your final examples are creating instances of functions that are then referenced though an object parameter. So this:
function myFirstFunc(param){};
obj.myFirst = myFirstFunc(); //not right!
obj.myFirst = new myFirstFunc(); //right!
obj.myFirst('something here'); //now calling the function
Says that you have an object that references an instance of a function. The key here is that if the function changes the reference you stored in obj.myFirst will not be changed.
While #kevin is basically right there is only functions in JS you can create functions that are much more like methods then functions, take this for example:
function player(){
this.stats = {
health: 0,
mana: 0,
get : function(){
return this;
},
set : function( stats ){
this.health = stats.health;
this.mana = stats.mana;
}
}
You could then call player.stats.get() and it would return to you the value of heath, and mana. So I would consider get and set in this instance to be methods of the player.stats object.
A function executes a list of statements example:
function add() {
var a = 2;
var b = 3;
var c = a + b;
return c;
}
1) A method is a function that is applied to an object example:
var message = "Hello world!";
var x = message.toUpperCase(); // .toUpperCase() is a built in function
2) Creating a method using an object constructor. Once the method belongs to the object you can apply it to that object. example:
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
this.name = function() {return this.firstName + " " + this.lastName;};
}
document.getElementById("demo").innerHTML = person.fullName(); // using the
method
Definition of a method: A method is a property of an object that is a function. Methods are defined the way normal functions are defined, except that they have to be assigned as the property of an object.
var myFirstFunc = function(param) {
//Do something
};
and
function myFirstFunc(param) {
//Do something
};
are (almost) identical. The second is (usually) just shorthand. However, as this jsfiddle (http://jsfiddle.net/cu2Sy/) shows, function myFirstFunc will cause the function to be defined as soon as the enclosing scope is entered, whereas myFirstFunc = function will only create it once execution reaches that line.
As for methods, they have a this argument, which is the current object, so:
var obj = {};
obj.func = function( ) {
// here, "this" is obj
this.test = 2;
}
console.log( obj.test ); // undefined
obj.func( );
console.log( obj.test ); // 2
The exact syntax you showed is because you can also do this:
function abc( ) {
this.test = 2;
}
var obj = {};
obj.func = abc;
obj.func( ); // sets obj.test to 2
but you shouldn't without good reason.
ecma document
4.3.31method :
function that is the value of a property
NOTE When a function is called as a method of an object, the object is
passed to the function as its this value.
It is very clear: when you call a function if it implicitly has a this (to point an object) and if you can't call the function without an object, the function deserves to name as method.
In javascript say I have:
var Person = (function () {
function Person(data) {
data = $.extend({
name: "",
age: 0
}, data);
this.name = data.name;
this.age = data.age;
}
return Person;
})();
Person.prototype.getName = function () {
return this.name;
};
...if I understand the 'this' keyword correctly in javascript, it can refer to pretty much anything from the window object to itself to anything in-between (e.g. callers of the object). My question is how the heck do I write methods like .getName() so that I know I'll always have a reference to the value stored in the person object's name property if I never can be sure what 'this' will refer to in that method? Say that .getName() is called and 'this' references the window object - how the do I get the value I need then?
I'm asking because I've inherited some code using pretty heavy prototyping and I'm running into all kinds of issues trying to reference properties and methods on objects from within themselves. Seems like I'm missing something but I've been looking into scope, closures, and other patterns all day and I can't get around this.
The value of this is set by the language according to how a function/method is called.
If you have an object with a method and you do:
obj.method()
Then, this will be set to point to the object inside of the method() function.
But, if you just get that method by itself like this:
var p = obj.method;
p();
Then, because there is no object reference in the actual function call, this will be set to either window or undefined depending upon whether you are in strict mode or not.
Additionally, the caller can specify exactly what they want this to be set to using obj.method.call() or obj.method.apply() or even p.call() or p.apply() from the previous example. You can look these methods up on MDN to see more details about how they work.
So, in your previous code, this should work:
function Person(data) {
data = $.extend({
name: "",
age: 0
}, data);
this.name = data.name;
this.age = data.age;
}
Person.prototype.getName = function () {
return this.name;
};
var p = new Person({name:"John"});
var n = p.getName(); // will return "John"
Working demo: http://jsfiddle.net/jfriend00/a7MkP/
If you needed to pass getName() to a third party library that won't call it with the object context, then there are a few options like this:
Anonymous function:
var myPerson = new Person("John");
callThirdParty(function() {
// callback that calls getName with the right object context
return myPerson.getName();
});
Using .bind() (not suported in some older browsers):
var myPerson = new Person("John");
var boundFn = myPerson.getName.bind(myPerson);
callThirdParty(boundFn);
From your own method:
var self = this;
callThirdParty(function() {
// callback that calls getName with the right object context
return self.getName();
});
FYI, there really is no reason for the self-executing function you have surrounding your Person constructor function. It just makes the code more complicated and adds no value in this case.
Yes, you are understanding the this keyword correctly.
how the heck do I write methods like .getName() so that I know I'll always have a reference to the value stored in the person object's name property
You can only do so by not using this, and in not using prototyping. Give each object a unique function that always refers to the original object:
function Person(data) {
data = $.extend({
name: "",
age: 0
}, data);
this.name = data.name;
this.age = data.age;
var that = this; // a reference variable always pointing to this instance
this.getName = function() {
// using the variable from the constructor closure
return that.name; // a quite useless getter
};
}
var john = new Person({name:"John"}),
getter = john.getName;
getter(); // "John"
I'm running into all kinds of issues trying to reference properties and methods on objects from within themselves
So with the above you can solve it by making all methods instance-specific. However, that undoes all the advantages of prototyping, and should not be used.
Instead, the one who calls a function (or a method) should be responsible to call it in the correct context:
john.getName();
If you really have to pass a function to someone which ignores that (like addEventListener), you can use magic stuff like .bind() or just apply the above pattern:
// from
addEventListener("click", john.sayHello); // will call the function in context of the DOM
// to
addEventListener("click", function() {
john.sayHello(); // correct thisValue
});
I'm a total Javascript newb, and I'm trying to wrap my head around OLN. What I'm encountering is that, when calling an object method from another method on the same object, the value of local value of 'this' in the called method is changing. Here's my code:
var generator = {
generateForLevelSkillAndCount : function(level, skill, count) {
var functionCall = this['generate_' + level + '_' + skill];
return functionCall(count);
},
generate_0_4 : function(count) {
return this.generate_generic_dots(count, 3);
},
generate_generic_dots : function(count, maxDots) {
/* do cool stuff and return it */
}
};
So, I call generator.generateForLevelSkillAndCount(0, 4, 20) and it works properly, calling generate_0_4(count). However, this is where it fails, with Chrome's Javascript console telling me "Uncaught TypeError: Object [object DOMWindow] has no method 'generate_generic_dots'."
I know enough to know that the problem is that the value of this in generate_0_4 is a DOMWindow object, rather than generator (which is what this is pointing to in generateForSkillLevelAndCount but I can't figure out why that would possibly be happening.
Update: I updated the example code per CMS's suggestion to get rid of eval, but the same error is being returned, so it's not just an eval bug.
In JavaScript, the context object (this) is set to the "global object" (window, in browsers) unless the method is accessed as an object property. Therefore:
var foo = { bar: function() { alert(this.baz); }, baz: 5 };
var bar = foo.bar;
var baz = 3;
foo.bar(); // alerts 5, from foo
foo["bar"](); // alerts 5, from foo
bar(); // alerts 3, from the global object
Note that all three function calls are to the exact same function!
So, in your code, you're assigning the desired method to functionCall and calling it directly, which causes the function to use window as its context object. There are two ways around this: access the method as an object property or use .call() or .apply():
function generateForLevelSkillAndCount1(level, skill, count) {
return this['generate_' + level + '_' + skill](count);
}
function generateForLevelSkillAndCount2(level, skill, count) {
var functionCall = this['generate_' + level + '_' + skill];
return functionCall.call(this, count);
}
First of all, I would encourage you to avoid eval where you don't need it, for example, in your fist function:
//...
generateForLevelSkillAndCount : function(level, skill, count) {
var functionCall = this['generate_' + level + '_' + skill];
return functionCall(count);
},
//...
You can use the bracket notation property accessor instead eval, it's unnecessary in this case.
Now, I guess you are trying your code on the Chrome's Console, and eval is failing because the console has a bug, when eval is invoked from a FunctionExpression (such as generateForLevelSkillAndCount), the evaluated code uses the Global context for its Variable Environment and Lexical Environment.
See this answer for more information on this bug.
Edit: After re-reading your code, the problem happens because you lose the base object reference when you assign the function to your functionCall variable, you can either:
Invoke the function directly, without using that variable:
//...
generateForLevelSkillAndCount : function(level, skill, count) {
this['generate_' + level + '_' + skill](count);
},
//...
Or still use your variable, but persist the this value:
//...
generateForLevelSkillAndCount : function(level, skill, count) {
var functionCall = this['generate_' + level + '_' + skill];
return functionCall.call(this, count);
},
//...
More info on this...
You can control the execution context of the method call by using call():
var generator = {
generateForLevelSkillAndCount : function(level, skill, count) {
return this['generate_' + level + '_' + skill].call(this, count);
},
generate_0_4 : function(count) {
return this.generate_generic_dots.call(this, count, 3);
},
generate_generic_dots : function(count, maxDots) {
/* do cool stuff and return it */
}
};
I'm as baffled as you are, but have you considered checking out what happens if you call generate_0_4 explicitly, instead of parsing it through eval()?
When you call generate_0_4 dynamically (using an implicit to_string()) it is returned to generateForLevelSkillAndCount as an ad-hoc function. Because it's in Window scope rather than Object scope, it can't reference this, and the internal call fails because this doesn't exist in that context.
Here's how to see what's happening:
generate_0_4 : function(count) {
throw(this);
return this.generate_generic_dots(count, 3);
},
With generator.generateForLevelSkillAndCount(0, 4, 1); you get [object Window] or [object DOMWindow].
With generator.generate_0_4(1); you get what you're expecting (and what works): [object Object] or #<an Object>.
This is a feature of Javascript: the value of this will depend on the object from which the function was called, not where it was defined. (Which makes sense when functions are first-class objects themselves.) this in most other contexts refers to the window object.
There are two common workarounds, using a wrapper function:
function bind(func, obj) {
return function() {
func.apply(obj, arguments);
}
}
or using a closure:
var self = this;
function generate_blah() {
// use self instead of this here
}
In your case, though, simply replacing
var functionCall = this['generate_' + level + '_' + skill];
return functionCall(count);
with
this['generate_' + level + '_' + skill](count);
would do the trick.