Created
December 20, 2021 20:43
-
-
Save markodayan/12bd5e1cde8c4cbae604ccd7cd3707ea to your computer and use it in GitHub Desktop.
Binding this context
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
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" |
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
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