【发布时间】:2011-04-30 00:49:12
【问题描述】:
我是 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。我在这里做错了什么?
【问题讨论】:
-
您在
prototype中有start有什么原因吗? -
Request.prototype设置为什么? -
我在这里有一个类似的问题:stackoverflow.com/questions/3198264/… 其中有很多有用的链接。关键在于 JavaScript 中的
this不是对被调用原型函数的“所有者”的常量引用,就像在大多数 OO 语言(如 Java)中一样。 -
@Matt:Request 是一个构造函数。 Request.prototype 默认为
new Object()。您添加到其中的任何内容都会自动成为使用new Request()创建的对象的属性。 -
我的意思是,这个问题比这个问题晚了 3 年提出的
标签: javascript class prototype