Languages
[Edit]
EN

JavaScript - get class method reference

1 points
Created by:
Dirask Community
5460

In this article, we would like to show you how to get a class method reference in JavaScript. 

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

References

Native Advertising
­čÜÇ
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

ÔŁĄ´ŞĆ­čĺ╗ ­čÖé

Join