【问题标题】:variable and function scope inside javascript object [duplicate]javascript对象内的变量和函数范围[重复]
【发布时间】: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 this page 也可能有帮助。

标签: javascript node.js scope


【解决方案1】:

当您以functionName() 调用函数时,而不是作为某个对象的方法,例如object.functionName(),其this 值在严格模式下默认为undefined,而全局对象在“马虎模式”下默认为undefined ”。

这里有两个选项:

将函数绑定到this,然后再将其传递给您的方法:

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

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

callback.call(this);


另一个问题是index 是您的init 方法中的一个局部变量,它会在init() 完成执行后立即消失。如果您希望您的对象具有 index 属性,请将其设为属性:
var serialCue = {
    index: 0,
    init:function(length_of_cue, handler){
.....

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-12-31
  • 1970-01-01
  • 1970-01-01
  • 2013-05-29
  • 1970-01-01
  • 2017-09-30
  • 1970-01-01
相关资源
最近更新 更多