javascript - Binded click loses context of my Class. JS -
I have a problem that I understand, but there is no way, how will it be known.
I have a simplified class:
function drawing tab (canvas_id) {this.canvas_id = canvas_id; Bind_events () function bind_events () (click) (function (e) {var canvas = get_canvas () // works do_something_in_the_instance_who_called_click ()} function get_canvas () {return document.getElementById (canvas_id)} function do_something_in_the_instance_who_called_click () {Warning (this.canvas_id) // fail!}}
Because when it clicks (which is not it ) inside, example But I need to change any one of them .. Is there any way, which can be many examples?
I do not really know how but get_canvas () work I'm using jQuery but probably not relevant to
This happens because you are calling the function without any object reference , but you can store this
value:
function DrawingTable (canvas_id) {var instance = this; // & lt; - `` Store this `value this.canvas_id = canvas_id; Click Bind_events () function bind_events () {$ (get_canvas ()) (function (e) {// Note that here `` this `value` will point to canvas gates,` example 'should also be used canvas = Get_canvas (); do_something_in_the_instance_who_called_click ();} function get_canvas () {return document.getElementById (canvas_id)} function do_something_in_the_instance_who_called_click () {alert (instance.canvas_id); // & lt; - use `this` value stored} }
When you call a function, the this
value is contained, for example:
obj.method ( );
If you have any will denote
value obj
, such as:
MyFunction ();
this
inside
Comments
Post a Comment