Javascript Class, var undefined in event listener -
this question has reply here:
preserve 'this' reference in javascript prototype event handler 3 answersvar foo = (function(){ function foo(){ this._s="string"; this.setbutton(); }; foo.prototype.setbutton = function(){ document.getelementbyid('id').addeventlistener('click', function(event) { alert(this._s); }); }; foo.prototype.method = function(){ alert(this._s); }; homecoming foo; })(); var fo = new foo(); fo.method();
i want bind event button, , execute function whic utilize 'private' var, when click button function correctly called can't see var this._s (it writes 'undefined'). if write fo.method() string correctly printed. here jsfiddle: http://jsfiddle.net/wlm1v4la/1/
you have set context(this) of function manually before passing it.
foo.prototype.setbutton = function () { var tmpfunc = function(evt){ alert(this._s); } //store function var boundfunction = tmpfunc.bind(this); //set context manually //pass function eventlistener document.getelementbyid('id').addeventlistener('click',boundfunction); };
javascript class oop
No comments:
Post a Comment