Created
August 18, 2023 16:26
-
-
Save suhailgupta03/1155e7f47a75b596243d7cc4991fe6e5 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let person = { | |
firstName: "Vikash", | |
lastName: "Sagar", | |
fullName: function() { | |
return this.firstName + " " + this.lastName; | |
} | |
} | |
console.log(person.fullName()); // Output: Vikash Sagar | |
let person1 = { | |
firstName: "John", | |
lastName: "Doe" | |
} | |
console.log(person.fullName.call(person1)); // Output: John Doe | |
// call function changes the context of this keyword to the person1 object. | |
let person2 = { | |
firstName: "Kapil", | |
lastName: "Jatav" | |
} | |
console.log(person.fullName.call(person2)); // Output: John Doe |
Author
suhailgupta03
commented
Aug 18, 2023
apply function
let person = {
firstName: "Vikash",
lastName: "Sagar",
fullName: function(arg1, arg2) {
console.log(arg1, arg2)
return this.firstName + " " + this.lastName;
}
}
console.log(person.fullName("arg1", "arg2")); // Output: Vikash Sagar
let person1 = {
firstName: "John",
lastName: "Doe"
}
console.log(person.fullName.apply(person1, ["hello", "world"])); // Output: John Doe
// apply and call are same but apply takes array as argument
bind function
let person = {
firstName: "Vikash",
lastName: "Sagar",
fullName: function(arg1, arg2) {
console.log(arg1, arg2)
return this.firstName + " " + this.lastName;
}
}
let person1 = {
firstName: "John",
lastName: "Doe"
}
let newFunction = person.fullName.bind(person1, "arg1", "arg2")
// bind returns a new function
// whereas call and apply executes the function
console.log(newFunction())
// newFunction now has a different context
// which is person1 and arguments are arg1 and arg2
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment