记录到控制台的JavaScript字段总是“未定义”
JavaScript field logged to console is always "undefined"
这是我第一次在JavaScript中使用对象,我使用了本教程中的1.1方法,我有这样的代码:
function MyClass() {
this.currentTime = 0;
this.start = function() {
this.currentTime = new Date().getTime();
console.log(this.currentTime); //this line prints the time i just set
this.intervalID = setInterval(this.step, 25);
};
this.step = function() {
var d = new Date().getTime();
console.log(this.currentTime); //always prints "undefined" to the console
};
this.stop = function() {
clearInterval(this.intervalID);
};
}
问题是在step()
函数中,console.log(this.currentTime)
总是打印"undefined",而this.currentTime
是在start()
函数中设置的。
为什么?我错过了什么?
您在每种情况下都使用功能this.fn
的范围,这就是为什么您不将其添加到MyClass
的范围。您必须存储this
对象并使用它来添加属性。
function MyClass() {
this.currentTime = 0;
var self = this;
this.start = function() {
self.currentTime = new Date().getTime();
console.log(self.currentTime); //this line prints the time i just set
self.intervalID = setInterval(self.step, 25);
};
this.step = function() {
var d = new Date().getTime();
console.log(self.currentTime); //always prints "undefined" to the console
};
this.stop = function() {
clearInterval(self.intervalID);
};
}
相关文章:
- 在wordpress一定时间后更改自定义字段
- Meteor-添加用户自定义字段的方法不起作用
- 微笑时间轴小部件添加自定义字段
- 使用具有用户定义字段的新请求者创建新的Zendesk票证
- WooCommerce-根据自定义字段添加费用
- 有了字段的名称,我如何用空白数据初始化对象的未定义字段
- 高级自定义字段按单选按钮值排序
- 从自定义DocuSign按钮添加信封自定义字段
- 如何使用inlineformset_factory添加自定义字段属性
- jQuery将地理补全输出到自定义字段
- 如何在自定义帖子类型中添加自定义字段
- 根据课程自定义字段在课程页面上添加链接
- 在Extjs中,获取自定义字段容器中的textfield值
- 角度过滤器分组依据过滤器返回一个“未定义”字段
- JavaScript/JQuery:添加未定义字段中的数字(带0)
- 表单上未定义字段的$error
- Javascript -从对象中删除未定义字段
- 主干模型中的自定义字段在集合中使用时未定义
- Javascript更新并忽略目标中的未定义字段
- Jade到HTML未定义字段