And why this method does not work?

function set(div) { this.div = div; this.func = function() { alert("work!"); } this.div.on("click", function(){ this.func(); }); } 
  • Uh ... what? That is, I wanted to say, formulate the question normally, format the code and make it syntactically valid. - Duck Learns to Take Cover

2 answers 2

A piece of code from a question does not work as intended, because the "parent" function and the call context that is nested in it have a different call context, this is a different value. More details about this can be found here .

Therefore, you can remember the context of calling the "parent" function in a local variable to which internal functions have access:

 function set(div) { this.div = div; var _this = this; this.func = function() { alert("work!"); } this.div.on("click", function() { _this.func(); }); } 
  • Yes it is! )) I will enter it. Thank you)) - modelfak
  • one
    @modelfak, then please mark the answer as accepted) - Duck Learns to Hide

And why this method does not work?

Because this inside .on() refers to .on() and not to set() . This is called this hiding. In such cases, use an additional variable, which is usually called it , me , that or similar names.