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
12.1k12 gold badges60 silver badges83 bronze badges
asked Jan 30, 2017 at 21:12
2
  • 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? Commented Jan 30, 2017 at 21:14
  • you haven't bound submit to anything, just pass an anonymous function to the constructor Commented Jan 30, 2017 at 21:14

2 Answers 2

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();
answered Jan 30, 2017 at 21:14
Sign up to request clarification or add additional context in comments.

Comments

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?

answered Jan 30, 2017 at 21:30

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.