Languages
[Edit]
EN

JavaScript - get class method reference

1 points
Created by:
Inayah-Alexander
767

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

References

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
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