【发布时间】:2023-03-20 08:09:01
【问题描述】:
我正在尝试建立一个超级原始的提示功能。本质上需要将一个操作重复n次。
var serialCue = {
init:function(length_of_cue, handler){
this.length_of_cue = length_of_cue;
this.handler = handler;
//this.handler();
var index = 0;
},
monitor: function(){
console.log(this.index);
// this.handler();
// this.index++;
// if(this.index>=this.length_of_cue){
// this.handler();
// }
},
eachIteration: function(callback){
console.log("yo");
callback();
},
startProcessing: function(){
for(var count=0;count<this.length_of_cue;count++){
this.eachIteration(this.monitor);
}
}
}
module.exports = Object.create(serialCue);
//IN APP.JS
var cue = require('./serial_cue.js');
cue.init(5,function(){
console.log("done done and done!");
});
cue.startProcessing();
输出返回索引值的“未定义”。我试图弄清楚为什么“this”在为该对象定义的所有方法中的行为都是可预测的,除了监视器。 JS 中的作用域仍然有点不稳定。
【问题讨论】:
-
index 是 init() 函数中的局部变量。您还应该查看 .bind() 函数:this.eachIteration(this.monitor.bind(this))。
-
@nnnnnn 但将其更改为 this.index = 0;产生相同的结果
-
是的,因为问题还有第二部分,因此我提到了 .bind()。请参阅下面的答案。 MDN's
thispage 也可能有帮助。
标签: javascript node.js scope