Implicit Binding
The this keyword refers to the context in which a function is executed. Its value is determined by how a function is invoked.
var workshop = {
teacher: "Kyle",
ask(question) {
console.log(this.teacher, question);
},
};
workshop.ask("What is implicit binding?");
// Kyle What is implicit binding?
In this code snippet, this.teacher is part of an object method, and its value is implicitly set to the object on which the method is called. This is known as implicit binding.
var workshopis an object with a propertyteacherand a methodask.- The
askmethod takes a parameterquestionand logs the combination ofthis.teacherand thequestionparameter. workshop.ask("What is implicit binding?");invokes theaskmethod on theworkshopobject.- When a method is invoked, the
thiskeyword inside the method refers to the object on which the method was called, which, in this case, isworkshop. - The
console.log(this.teacher, question);logs the value ofthis.teacher(which is "Kyle" because it refers to theteacherproperty of theworkshopobject) along with the providedquestionparameter.