2013-06-24 58 views
2

在我的對象的構造函數中,我創建了一些span標記,並且需要將它們引用到同一對象的方法中。將點擊事件綁定到類中的方法

這裏是我的代碼示例:

$(document).ready(function(){ 
    var slider = new myObject("name"); 
}); 

function myObject(data){ 
    this.name = data; 

    //Add a span tag, and the onclick must refer to the object's method 
    $("body").append("<span>Test</span>"); 
    $("span").click(function(){ 
     myMethod(); //I want to exec the method of the current object 
    }); 


    this.myMethod = myMethod; 
    function myMethod(){ 
     alert(this.name); //This show undefined 
    } 

} 

有了這個代碼調用該方法,但它不是一個參考對象(this.name顯示未定義) 我該如何解決呢?

非常感謝!

+2

其因爲'this'將參照當前範圍(這將是觸發事件它即點擊) –

回答

5

一個簡單的方法來實現這一目標:

function myObject(data){ 
    this.name = data; 

    // Store a reference to your object 
    var that = this; 

    $("body").append("<span>Test</span>"); 
    $("span").click(function(){ 
     that.myMethod(); // Execute in the context of your object 
    }); 

    this.myMethod = function(){ 
     alert(this.name); 
    } 
} 

的另一種方法,使用$.proxy

function myObject(data){ 
    this.name = data; 

    $("body").append("<span>Test</span>"); 
    $("span").click($.proxy(this.myMethod, this)); 

    this.myMethod = function(){ 
     alert(this.name); 
    } 
} 
+0

或者我們可以只使用'data'而不是'this.name' –

+0

@GokulKav或$ .proxy,就像我剛剛添加的那樣。或綁定。有多種解決方案 – bfavaretto

+0

是.. upvoted你的解決方案 –

相關問題