2013-11-09 37 views
1

我使用Javascript,我想創建授權類。Javascript函數實例和調用

我的代碼是

function Auth() { 
    this.action; 
    this.run = function() { 
     $("#auth-dialog-id").dialog({ 
      width: 400, 
      height: 250, 
      modal: true, 
      buttons: { 
       OK: function() { 
        this.action(); 
        $(this).dialog("close"); 
       }, 
       Cancel: function() { 
        $(this).dialog("close"); 
       } 
      } 

     }); 
    }; 
} 

呼叫

auth = new Auth(); 
    auth.action = a; 
    auth.run(); 
} 
function a() { 
    alert("test"); 
} 

,但我有錯誤

對象#有沒有方法 '動作'

任何人可以幫助我嗎?

+5

嘗試用'auth.action'代替'this.action =一個;' –

+2

供參考: 'this.action;'實際上什麼都不做。它的目的是作爲文檔嗎? –

+0

我很抱歉。我已更正了我的問題 – javagc

回答

0

由於您已更正this.action = a問題,因此問題出在OK按鈕回調上下文中。在按鈕內部單擊回調this不會引用auth實例。

這裏一個可能解決方案是使用封閉變量如下面給出

function Auth() { 
    var self = this; 
    this.run = function() { 
     $("#auth-dialog-id").dialog({ 
      width: 400, 
      height: 250, 
      modal: true, 
      buttons: { 
       OK: function() { 
        self.action(); 
        $(this).dialog("close"); 
       }, 
       Cancel: function() { 
        $(this).dialog("close"); 
       } 
      } 

     }); 
    }; 
} 

auth = new Auth(); 
auth.action = a; 
auth.run(); 

演示:Fiddle

+0

謝謝。我明白我的錯誤,我接受你 – javagc