绑定点击会丢失我的班级的上下文。 JS [英] Binded 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.
我有一个类简化为:
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 atributes 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
推荐答案
这是因为你在没有任何对象上下文的情况下调用该函数,但您可以存储此
值:
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
value将指向 obj
,如果您在没有任何基础对象的情况下进行函数调用,例如:
The this
value will point to obj
, if you make a function call without any base object, e.g.:
myFunction();
这个
myFunction
中的值将指向全局对象。
The this
value inside myFunction
will point to the global object.
这篇关于绑定点击会丢失我的班级的上下文。 JS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!