2010-06-15 35 views
0

我有這個問題,我可能理解,但不知道如何處理,如果有辦法。綁定的點擊會丟失我的課程的上下文。 JS

我已經簡化爲這樣一個類:

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! 
    } 

} 

因爲當點擊()被調用,它看起來是不是實例裏面了,但我需要從那裏改變atributes。有沒有辦法,因爲這可能是多個實例?

我真的不知道如何,但get_canvas()的作品:)

我使用jQuery但可能不相關

回答

3

那是因爲你沒有任何對象上下文調用該函數,但你可以存儲this值:

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 
    } 

} 

this值是隱含當你做一個函數調用,例如設置:

obj.method(); 

this值將指向obj,如果你犯了一個函數調用沒有任何基本對象,例如:

myFunction(); 

myFunctionthis值將指向全局對象。

+0

+1 Great Great Explanation!將繼續打開幾個小時 – 2010-06-15 14:29:57