JavaScript - get class method reference

1 points
Created by:

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() {

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


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.

❤️💻 🙂