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;
}

}

我的目标是点击 htmlWindow,执行 DialogWindow 的功能。但是,每当我这样做时,所有 DialogWindows 属性都会返回未定义。如果我替换该行:

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

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

然后函数 test() 立即触发并工作(即将 this.contents 打印到控制台)。但是,如果我保持原样(即我等待单击以使 test() 函数触发),那么它将 undefined 打印到控制台。

4

1 回答 1

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

在这种情况下,我更喜欢使用前一种方法

于 2013-08-30T02:30:19.130 回答