最佳答案
我刚接触 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。我做错了什么?