2013-08-30 25 views
1
function DialogWindow(contents, clickEvent){ 
// given a contents we can create a DialogWindow of that content 
this.contents = contents; 
this.domElement = $(".hideMe"); 

this.test = function(){ 
    console.log(this.contents); 
} 

$("div").click(this.test); //<-note this spot 

/* 
This function simply returns the html representation of the contents 
This function should be called withen WindowPage so that it can fully figure out what 
Arguments: 
    container: the container that containes the WindowPage that this is apart of 
    lanes: the number of lanes on the page. Defined as: lanes = (number of columns in WindowPage) * 3 + 1 
*/ 
this.toHtml = function(container, lanes){ 

    var dialogWidth = container.width()/(lanes/2); 
    var dialogSep = container.width()/lanes; 

    var htmlWindow = jQuery('<div/>', { 
     id: "dialogWindow" 
    }).css("width", dialogWidth).css("height", dialogWidth).css("position","absolute"); 

    jQuery(this.contents.toHtml()).appendTo(htmlWindow); 

    this.domElement = htmlWindow; 

    return htmlWindow; 
} 

}JavaScript和jQuery,創建並使用一個對象。屬性返回undefined

我的目標是讓htmlWindow的點擊,執行DialogWindow的功能。然而每當我這樣做時,所有的DialogWindows屬性都會返回undefined。如果我更換行:

$("div").click(this.test); 

$("div").click(this.test()); 

然後在功能測試()imediatelly火災和工程(即打印this.contents到控制檯)。但是,如果我保持原樣(即等待點擊使test()函數觸發),那麼它將未定義的控件打印出來。

回答

0

這是因爲this內部test不指向DialogWindow對象,它指向點擊的DOM元素

一種解決方案是通過一個自定義的執行代理使用事件回調$.proxy()

this.test = function(){ 
    console.log(this.contents); 
} 
$("div").click($.proxy(this.test, this)); //<-note this spot 

另一種流行的解決方案是使用閉合變量

var self = this 
this.test = function(){ 
    console.log(self.contents); 
} 
$("div").click(this.test); //<-note this spot 

在此場景我寧願使用以前的方法

+0

所以我一直在這一段時間。大約5分鐘後,我發佈了這個,我發現我可以用var self =這個想法做到這一點。所以這就是我一起去的。我很高興看到我至少沒有做一些完全瘋狂的事情。 – user2731337

相關問題