JavaScript "this" references wrong object

You might need to make a tweak like this:

function someObj() {
    var that = this;

    this.someMethod1 = function() {
        var elementBtn = document.getElementById('myBtn');
        elementBtn.onclick = function() { 
            that.someMethod2();
        };
    };
    this.someMethod2 = function() {
       alert('OK');
    };
}

"that" captures the scope you are after.


The function keyword changes scope. One solution is to maintain the reference to the "this" that you want to use.

Try the following:

function someObj() {
   var self = this;
   this.someMethod1 = function() {
      var elementBtn = document.getElementById('myBtn');
      elementBtn.onclick = function() { 
         self.someMethod2(); //NOTE self
      };
   };
   this.someMethod2 = function() {
      alert('OK');
   };
}