Accessing instance method of JavaScript using this keyword inside each()

As a Java or C# developer, this keyword can we be used in instance method or in constructor to access variables or instance methods.

JavaScript is a prototype-based scripting language and supports Object-Oriented features and this keyword too.

JQuery is most popular JavaScript Cross-Platform library and 99.99% developers uses it for web development. JQuery has $.each() to iterate jQuery object.


In above example, when elements iterate with each, it create dynamic object inside the method named this. Now using this object we can have the access of each element. in this example using this we can get the value.

How this can be used in Javascript class. Here is the example.

Now what if we use $.each() in Javascript class and want to use <strong>this </strong>keyword as Javascript class’s instance as well as to get element in the $.each iterator?

When employee.printInfoIfSalary(10000) executed, there is no way using this or with this to call getInfo() method within each method of jQuery and it will throw uncaught TypeError: undefined is not a function.

using this Uncaught TypeError: undefined is not a function

How can we fix this? I have spent more than 1 hour to solve this problem. but finally I figured it out. Here is working code.

Working code to fix above issue.

In this example we define thisObj = this, reference of this variable to thisObj, and now thisObj can be reference as instance of this class.

I hope this example with help you to understand when jQuery and OOPs concepts needs to use together.

Code for this example: