绑定单击会丢失我的课程的上下文。 JS [英] Bound click loses context of my Class. JS
问题描述
我有一个我可能理解的问题,但如果有办法,不知道如何处理。
I have this problem that I probably understand but don't know how to handle, if there is a way.
我有一个简化的类,如下所示:
I have a class simplified as this:
function DrawingTable(canvas_id){
this.canvas_id = canvas_id;
bind_events()
function bind_events(){
$(get_canvas()).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(){
alert(this.canvas_id) //fail!
}
}
因为当 click()
为其外观调用时,此不再在实例内部,但是我需要从那里更改属性。有办法,因为可能有多个实例?
Because when the click()
is invoked for what it looks this is not inside the instance anymore, but I need to change attributes from there. Is there a way, given that may be multiple instances?
我真的不知道如何,但是get_canvas()起作用了:)
I don't really know how but the get_canvas() works :)
我' m使用jQuery但可能不相关
I'm using jQuery but likely not relevant
推荐答案
发生这种情况是因为您在没有任何 object上下文的情况下调用了函数,但您可以存储此
值:
That happens because you are calling the function without any object context, but you can store the this
value:
function DrawingTable(canvas_id){
var instance = this; // <-- store `this` value
this.canvas_id = canvas_id;
bind_events()
function bind_events(){
$(get_canvas()).click(function(e){
// Note also that here the `this` value will point to the
// canvas elemenet, `instance` should be used also
var 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); // <-- use stored `this` value
}
}
此
的值在进行函数调用时被隐式设置,例如:
The this
value is implicitly set when you make a function call, for example:
obj.method();
this $如果您在没有任何基础对象的情况下进行函数调用,则c $ c>的值将指向
obj
,例如:
myFunction();
此$ c $
myFunction
中的c>值将指向全局对象。
The this
value inside myFunction
will point to the global object.
这篇关于绑定单击会丢失我的课程的上下文。 JS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!