2013-03-13 86 views
1

此刻我走到了這一步。如何在JavaScript中調用當前對象的公共方法?

function Class() { 

    var privateMethod = function() { 
     return 'private' 
    } 

    this.publicMethod = function() { 
     return 'public' 
    } 

    var _constructor = function() { 
     $(document).on('click', _onClick) 
    } 

    var _onClick = function() { 
     // My error is `this`, focus now on the click event, but I need the object itself 
     console.log(privateMethod()) 
     console.log(this.publicMethod()) 
    } 

    _constructor() 
} 


$(document).ready(init) 

function init() { 
    new Class() 
} 

問題是,在點擊事件中,我無法調用publicMethod。 我可以調用私有方法。

我該如何做到這一點?

+1

也許你應該嘗試javascript模塊模式。 http://briancray.com/posts/javascript-module-pattern – pbaris 2013-03-13 14:56:09

+0

這看起來很混亂。但我會試試看,謝謝! – 2013-03-13 15:02:26

回答

2

的問題是,在你的處理器,你失去了你的上下文(this不再意味着你的類的實例,它,而不是意味着你的觸發事件的對象,你需要創建一個封閉作用域確定的this版本舉行到

var self = this; 
var _onClick = function() { 
    // My error is `this`, focus now on the click event, but I need the object itself 
    console.log(privateMethod()) 
    console.log(self.publicMethod()) 
} 
1

這種情況下,你必須在onclick一個範圍問題,this指向一個不同的對象比你期望的。在你的情況下,它是document

var that = this; 
var _onClick = function() { 
    // My error is `this`, focus now on the click event, but I need the object itself 
    console.log(privateMethod()) 
    console.log(that.publicMethod()) 
} 

Running Example

+0

也謝謝,但我只能接受1個答案,你們都是對的:) – 2013-03-13 15:09:28

相關問題