1

On my index.html, I have this code,

$(document).ready(function() {
    var self = this;
    var submit = function() {
        alert("Test");
    }
    const form = new Form(self.submit);
})

In my Form.js, I have this code,

class Form() {
    constructor(func) {
        var self = this;
        // ...
        $("submitBtn").click(function(e) {
           e.preventDefault();
           self.func();
        });
        // ...
    }
}

Why my function is not executing after the submitBtn is clicked? I used self to get the "this" value. I cant use "new Form(self.submit())" because It will execute the function once the line is read.

Sébastien
  • 11,860
  • 11
  • 58
  • 78
JMA
  • 974
  • 3
  • 13
  • 41
  • Well, you do pass "func" to your constructor, but then you do nothing with it... Is this your whole code, or did you remove parts of it? – nibnut Jan 30 '17 at 21:14
  • you haven't bound `submit` to anything, just pass an anonymous function to the constructor – Daniel Lizik Jan 30 '17 at 21:14

2 Answers2

3

Your submit function is a local variable, not a property of this. Thus you need:

const form = new Form(submit);

Similarly, in your constructor, func doesn't have anything to do with self; it should just be

  func();
Pointy
  • 405,095
  • 59
  • 585
  • 614
1

Pointy answers the question. I just want to add that constructor is a place where you usually declare and initialize instance properties, and it's better to register click event in a class method, something like:

class Form{
  constructor(){}
  click(func){
     $("submitBtn").click((e)=>{
           e.preventDefault();
           func();
        });
  }

}

Also you dont need to cache the scope var self = this as long as you use arrow function. This answer could be useful Advantages of using prototype, vs defining methods straight in the constructor?

Community
  • 1
  • 1
andrey
  • 1,867
  • 3
  • 21
  • 34