2016-02-20 80 views
0

我想建立一個超級原始的提示函數。基本上需要重複操作n次。JavaScript對象內部的變量和函數範圍

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(); 

對於索引的值,輸出返回「undefined」。我試圖找出爲什麼「this」在爲monitor對象定義的所有方法中可預測地行爲。 JS中的範圍仍然有點不穩定。

+0

index是init()函數中的局部變量。您還應該查看.bind()函數:this.eachIteration(this.monitor.bind(this))。 – nnnnnn

+0

@nnnnnn但將其更改爲this.index = 0;產生相同的結果 – dima

+0

是的,因爲問題的第二部分,因此我提到.bind()。請參閱下面的答案。 [MDN's this' page](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this)也可能有所幫助。 – nnnnnn

回答

2

當你調用一個函數作爲functionName(),而不是某個對象的方法,如object.functionName(),其this值將默認爲undefined嚴格模式,並在「馬虎模式」全局對象。

兩個位置的選項有:

綁定功能this傳遞到您的方法之前:

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

或者,如果你想在eachIteration回調總是有當前thisthis值,您可以使用回調的.call()方法:

callback.call(this); 


另一個問題是 index是您的 init方法中的局部變量,只要 init()完成執行就會立即消失。如果您希望您的對象具有 index屬性,請將其設爲屬性:

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

基於建議的解決方案提出一個快速要點。 https://gist.github.com/Digi-D/7de9ad7952c0b07f9d5d thnx! – dima