Search code examples
javascriptdom-events

JavaScript context in inner event function


I am trying to access the properties of the MainObj inside the onclick of an elem. Is there a better way to design it so the reference wont be to MainObj.config.url, but to something like this.config.url?

Sample code:

var MainObj = {
      config: { url: 'http://www.example.com/'},
      func: function()
      {
          elem.onclick = function() {
           var url_pre = MainObj.config.url+this.getAttribute('href');
                    
           window.open(url_pre, '_new');
          };
      }

}

Solution

  • 'this' inside the object always refers to itself (the object). just save the context into a variable and use it. the variable is often called '_this', 'self' or '_self' (here i use _self):

    var MainObj = {
      config: { url: 'http://www.mysite.com/'},
      func: function()
      {
          var _self = this;
           elem.onclick = function() {
           var url_pre = _self.config.url+this.getAttribute('href');
    
           window.open(url_pre, '_new');
          };
      }
    }