0

When this keyword is used in jQuery listener, it refers to the DOM element. Is there a way for it to refer to parent function?

Let's use this simple snippet:

var myApp = {
  init: function() {
    // `this` refer to myApp
    $('.my-button').on('click', this.clickListener);
  },
  
  clickListener: function(e) {
    e.preventDefault();
  
    // now `this` refer to `.my-button`
    // how to make it refer to myApp?
    this.printLorem();
  },
  
  
  printLorem: function() {
    console.log('lorem ipsum dolor sit');
  }
};

myApp.init();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<button class="my-button">Print Lorem Ipsum</button>

I have been wondering about this for years, so far I simply type in the var name like myApp.printLorem() instead of this.printLorem() but there's got to be cleaner way.

hrsetyono
  • 4,474
  • 13
  • 46
  • 80
  • 1
    Three ways: **1.** Cache `this` **2.** `bind(this)` **3.** Arrow Function – Tushar Jul 13 '17 at 04:45
  • One [might argue](https://stackoverflow.com/questions/10711064/javascript-object-literal-reference-in-own-keys-function-instead-of-this) that `myApp.printLorem` already is the cleaner way :-) – Bergi Jul 13 '17 at 04:46

0 Answers0