Accessing Instance Method of JavaScript Using This Keyword Inside Each()

Jun 9, 2014

3 mins read

As a Java or C# developer, this keyword can we be used in instance method or in the 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 use it for web development. JQuery has $.each() to iterate jQuery object.

Like

1
2
3
4
5
6
7
8
9
var sum = 0;

var values = [ 10, 20, 30, 40, 50 ];

$.each( values, function(){
sum += this;
});

console.log( sum ); //sum would be 150

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

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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
function Employee (position,name) {
    this.position = position;
    this.name = name;
    this.getInfo = function() {
         return this.name + ' ' + this.position +" earns "+this.getSalary();
    };

    this.getSalary = function(){
      return "$10,000";
    }
}

var employee = new Employee("Spy","James Bond");

console.log( employee.getInfo() );  // James Bond Spy earns $10,000

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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
function Employee (position,name) {
    this.position = position;
    this.name = name;

    this.getInfo = function() {
        return this.name + ' ' + this.position +" earns "+this.getSalary();
    };

    this.getSalary = function(){
      return "$10,000";
    }

    this.printInfoIfSalary=function(salary){

      var salaryList = {"Manager": 20000, "Spy": 10000, "mentor": 5000};

      $.each( salaryList, function(key){
          if(salary==this){

           //Now what If I want to call getInfo from here
            this.getInfo(); //Wont Work
            getInfo(); //wont work

          }
      });
    }
}

var employee = new Employee("Spy","James Bond");

console.log( employee.getInfo() );  // James Bond Spy earns $10,000

employee.printInfoIfSalary(10000);

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.

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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
function Employee (position,name) {
    this.position = position;
    this.name = name;
    //define thisObj as globle variable and give this reference
    //now thisObj can used as this if class instance
    var thisObj = this;
    this.getInfo = function() {
        return this.name + ' ' + this.position +" earns "+this.getSalary();
    };

    this.getSalary = function(){
      return "$10,000";
    }

    this.printInfoIfSalary=function(salary){

      var salaryList = {"Manager": 20000, "Spy": 10000, "mentor": 5000};

      $.each( salaryList, function(key){
          if(salary==this){

          //Now what If I want to call getInfo from here

          console.log(  thisObj.getInfo() ); //will Work

            //getInfo(); or this.getInfo() //wont work
          }
      });
    }
}
var employee = new Employee("Spy","James Bond");

console.log(employee.printInfoIfSalary(10000));

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

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

Code for this example:  https://codebeautify.org/htmlviewer/e1ce80

Sharing is caring!