JavaScript 对象中的变量和函数作用域

variable and function scope inside javascript object

本文关键字:函数 作用域 变量 对象 JavaScript      更新时间:2023-09-26

我正在尝试建立一个超级原始的提示函数。基本上需要重复一个操作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中的范围仍然有点不稳定。

当你调用一个函数作为functionName(),而不是作为某个对象的方法,如object.functionName(),它的this值将默认为严格模式下undefined,全局对象在"草率模式"下

这里有两个选项:

在将函数传递到方法之前,将函数绑定到 this

this.eachIteration(this.monitor.bind(this));

或者,如果您希望 eachIteration 中的回调始终将当前this作为其this值,则可以使用回调的 .call() 方法:

callback.call(this);

<小时 />另一个问题是indexinit方法中的一个局部变量,一旦init()完成执行,它就会消失。如果希望对象具有index属性,请使其成为属性:

var serialCue = {
    index: 0,
    init:function(length_of_cue, handler){
.....