我是JavaScript新手。就我真正完成的工作而言,新内容是对现有代码进行了调整,并编写了少量的jQuery。

现在,我试图编写一个带有属性和方法的“类”,但是我在使用方法时遇到了麻烦。我的代码:

function Request(destination, stay_open) {
    this.state = "ready";
    this.xhr = null;
    this.destination = destination;
    this.stay_open = stay_open;

    this.open = function(data) {
        this.xhr = $.ajax({
            url: destination,
            success: this.handle_response,
            error: this.handle_failure,
            timeout: 100000000,
            data: data,
            dataType: 'json',
        });
    };

    /* snip... */

}

Request.prototype.start = function() {
    if( this.stay_open == true ) {
        this.open({msg: 'listen'});
    } else {

    }
};
//all console.log's omitted

问题是,在Request.prototype.start中,this是未定义的,因此if语句的计算结果为false。我在这里做错了什么?

最佳答案

您如何调用启动函数?

这应该可以工作(是关键)

var o = new Request(destination, stay_open);
o.start();

如果直接像Request.prototype.start()这样调用它,this将引用全局上下文(浏览器中的window)。

另外,如果未定义this,则会导致错误。 if表达式的结果不为false。

更新:不是根据声明而是通过调用来设置this对象。这意味着如果将function属性分配给x = o.start之类的变量并调用x(),则start内部的this不再引用o。这是您执行setTimeout时发生的情况。要使其正常工作,请执行以下操作:
 var o = new Request(...);
 setTimeout(function() { o.start(); }, 1000);

07-24 09:46
查看更多