Skip to content

Instantly share code, notes, and snippets.

@suhailgupta03
Created August 18, 2023 16:26
Show Gist options
  • Save suhailgupta03/1155e7f47a75b596243d7cc4991fe6e5 to your computer and use it in GitHub Desktop.
Save suhailgupta03/1155e7f47a75b596243d7cc4991fe6e5 to your computer and use it in GitHub Desktop.
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
@suhailgupta03
Copy link
Author

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

@suhailgupta03
Copy link
Author

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