2012-05-24 33 views
-1

有沒有一種方法可以從同一個對象內配置的jquery按鈕單擊調用公共方法?下面我向你展示我已經試過的多種方式從自己的對象javascript調用的公共方法?

var myClass = new MyClass(); 

function MyClass() { 
    this.func1 = function() { 
     alert("Hello World"); 
    } 

    var me = this;  
    $("#my-button").click(function(){ 
     //func1(); //dont work (wold like) 
     //this.func1(); //dont work (would like) 
     me.func1(); //Work! but is not correct way to do it 
     myClass.func1(); //Work! but the idea its that recognize itself widthout call public instance 
    }); 
} 

其他的方法?

+3

_me.func1(); //工作!但不是正確的做法_這是怎麼回事? –

+0

你是什麼意思的「公共方法」? – Phrogz

+0

@ParthThakkar我會問同樣的問題 – fcalderan

回答

1

嘗試了這一點:

var myClass = new MyClass(); 

function MyClass() { 
    var myFunc = function() { 
     alert("Hello World"); 
    } 
    this.func1 = myFunc; 

    $("#my-button").click(function(){ 
     myFunc(); 
    }); 
} 
2

me.func1()實際上是做了正確的方式,但我相信約定是命名爲「自我」,而不是「我」。

+2

最佳做法?在什麼基礎上?稱之爲慣例。 –

+0

哈哈我沒有基礎,這就是爲什麼我以「我相信」爲先。約定的約定更好。 – Porco

+0

誤讀(更好,沒有閱讀)......哎呀! –

0

由於this單擊處理程序內是指my-buttonthis.func1()將無法​​正常工作。 func1()將不起作用,因爲當最終觸發點擊處理程序時,它將處於不同的上下文中,並且在該上下文中沒有任何意義。你的解決方案很好。

相關問題