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:
xxxxxxxxxx
1
window.text = 'window text'
2
3
const object = {
4
text: 'object text',
5
print: function() {
6
console.log(this.text);
7
}
8
};
9
10
object.print(); // 'object text' // works fine
11
12
var print = object.print;
13
print(); // 'window text' // incorrect use, common mistake
14
15
var objectPrint = object.print.bind(object); // <---- solution
16
17
objectPrint(); // 'objext text' // works fine after binding