EN
JavaScript - get class method reference
1
points
In this article, we would like to show you how to get a class method reference in JavaScript.
The below example presents the use of bind
method to create a reference to a function that uses the correct context (from the object
).
We use bind
method to avoid one of the most common mistakes in JavaScript - trying to assign a method from an object to a new variable to use it later.
Practical example:
// ONLINE-RUNNER:browser;
window.text = 'window text'
const object = {
text: 'object text',
print: function() {
console.log(this.text);
}
};
object.print(); // 'object text' // works fine
var print = object.print;
print(); // 'window text' // incorrect use, common mistake
var objectPrint = object.print.bind(object); // <---- solution
objectPrint(); // 'objext text' // works fine after binding