JMA
JMA

Reputation: 994

Pass function to javascript class

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.

Upvotes: 1

Views: 85

Answers (2)

andrey
andrey

Reputation: 1977

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?

Upvotes: 1

Pointy
Pointy

Reputation: 413720

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();

Upvotes: 3

Related Questions