-2

I'm trying to achieve the task shown by the example code below, but get this error :

Uncaught TypeError: this.myFunction is not a function

I know i'm doing something wrong but don't know the right way to do it : how can i access the 'this' object inside a Jquery listener ?

Thanks in advance !

var MyClass = function () {
    return {
        myFunction: function () {
            console.log('Do something');
        },
        myOtherFunction: function() {
            $('#myButton').on('click', function () {
                this.myFunction(); // here i get the error
            });            
        }
    }
}
delphirules
  • 6,443
  • 17
  • 59
  • 108
  • You need to capture this, or bind it. Note there are many dupes of... this, so it should be trivially searchable. – Dave Newton Sep 04 '18 at 14:01
  • or use arrow function to get this from parent's scope – Lyubomir Sep 04 '18 at 14:01
  • Could someone provide an example code that works, please ? – delphirules Sep 04 '18 at 14:02
  • `this` has a specific meaning inside a jQuery event hander - it's the element that triggered the event. You could wrap the event handler inside an IIFE and pass `this` as a parameter, just giving it a different name. – Reinstate Monica Cellio Sep 04 '18 at 14:02
  • 2
    Your code, fixed: https://jsfiddle.net/t4dokeqr/ - ES6 `class` version: https://jsfiddle.net/6cjnwf35/ - improved: https://jsfiddle.net/7drh0g21/ –  Sep 04 '18 at 14:05
  • @ChrisG Worked, thank you very much ! Feel free to post as answer, i'll accept it. I'm glad SO still have people prone to help, instead of provide only clues to the solution or simply minus the question... Thank you ! – delphirules Sep 04 '18 at 14:08
  • 1
    @delphirules The way SO works is that when there's a duplicate, or it's easily searchable, you'll be told that. While I didn't downvote, I'm sympathetic to whoever did, because this is a very common question, with many answers, both on SO and the web in general. I'm also sympathetic to not knowing something, because we've all been there-tempered with believing when answers are already available, self-service is both quicker and more educational. Plugging your question title into Google, for example, brings up many SO answers as well as others. Just sayin'. – Dave Newton Sep 04 '18 at 14:16
  • @DaveNewton Thanks for your comments. – delphirules Sep 04 '18 at 17:05

1 Answers1

1

You can use arrow function, it takes care of auto binding and you can stay away with scope related issues

ES6:

  var MyClass = () => {
        return {
           myFunction: () => {
               console.log('Do something');
           },
          myOtherFunction: () => {
               $('#myButton').on('click', () => {
                   this.myFunction(); // this will be available here
               });            
           }
       }
   }
Hemadri Dasari
  • 32,666
  • 37
  • 119
  • 162