We know that functions are a special kind of objects in JavaScript. So they have access to some methods and properties. To prove functions are objects, we can do something like this, for example:
function greeting() {
console.log('Hello World');
}
greeting.lang = 'English';
// Prints 'English'
console.log(greeting.lang);
JavaScript also provides some special methods and properties to every function object. So every function in JavaScript inherits those methods. Call, bind, and apply are some of the methods that every function inherits.
call( )
The call( ) allows for a function/method belonging to one object to be assigned and called for a different object.
Using the call method we can do a function borrowing.
We can borrow a method from some object and use it with the data of some other object.
We can do like following-
let name = {
firstName: "nouman",
lastName: "shah",
}
let printFullName = function () {
console.log(this.firstName + " " + this.lastName)
}
printFullName.call(name)
//nouman shah
let name2 = {
firstName: "Ali",
lastName: "khan"
}
printFullName.call(name2)
In call( ), we pass arguments individually.
let printFullName = function (hometown, gender, job) {
console.log(this.firstName + " " + this.lastName + " " + "from" + " " + hometown + " " + gender + " " + job)
}
printFullName.call(name, "Pakistan", "Male", "Software Engineer")
apply( )
The apply() method is similar to call(). The difference is that the apply() method accepts an array of arguments instead of comma-separated values.
printFullName.apply(name,["Pakistan","Male", "Software Engineer"])
bind( )
bind method looks similar to call but instead of directly calling the method, the bind method binds the printFullName with an object and returns a copy of that.
let printMyName=printFullName.bind(name)
printMyName();
// nouman shah
What it will do is that it will create a copy of printFullName and it will bind that with name object and will return a function that can be called later.
The difference between call() and bind() is that the call() does not create a new copy of the function,
We can also pass extra arguments to the bind method. The general syntax for this is function.bind(this, arg1, arg2, ...).
If you have any questions or suggestions please let me know.
Top comments (4)
I think u could show practical use cases.
sure, I will also share practical use cases.
Thanks
I think you forgot to speak about "the context". That's where, for example,
bind()
is very useful.Use bind() when you want a function that always runs with a specific value.