Skip to content

Instantly share code, notes, and snippets.

@markodayan
Created December 20, 2021 20:43
Show Gist options
  • Save markodayan/12bd5e1cde8c4cbae604ccd7cd3707ea to your computer and use it in GitHub Desktop.
Save markodayan/12bd5e1cde8c4cbae604ccd7cd3707ea to your computer and use it in GitHub Desktop.
Binding this context
const Person = {
firstName: "Lawrence",
lastName: "Eagles",
sayName: function () {
setTimeout(function() {
console.log("my fullname is " + this.firstName + " " + this.lastName)
}.bind(this), 100) // binds this here.
}
}
console.log(Person.sayName()) // returns "my fullname is Lawrence Eagles"
const developer = {
firstName: "John",
lastName: "Doe",
getDevName: function() {
let fullName = this.firstName + " " + this.lastName;
return fullName;
}
}
const logDevName = function () {
console.log('logged: ' + this.getDevName());
}
// binds the `this`in the boostedLogDevName function to the developer object.
const boostedLogDevName = logDevName.bind(developer)
boostedLogDevName(); // "developer's name is:John Doe"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment