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(); }); } 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(); }); } 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(); }); } 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.
Source: https://ru.stackoverflow.com/questions/422631/
All Articles