2016-11-16 80 views
0

我試圖在Angular 2項目中包含一箇舊的JavaScript模塊,並且遇到了訪問父範圍的問題。將父範圍添加到匿名函數 - JavaScript到Angular 2

let testString = "Parent Scope Accessed!"; 

Object.keys(data).forEach((function(Key, Index) { 
    if(filter.type == 'parameter') { 
     Object.keys(dirArray).forEach(function(dirKey, dirIndex) { 
     linkArray = dirArray[dirKey]; 
     if(filter.dir == 2) { //Direction filter 
      Object.keys(linkArray).forEach(function(linkKey, linkIndex) { 
      if(filter.type != 'sub')) { 
       dataObject = linkArray[linkKey]; 

       //ERROR with scoping occurs below. Need to add parent scope. 
       console.log(this.testString); 
      } 
      }); 
     } 
     }); 
    } 
})); 

我一直試圖做這樣的事情:

let testString = "Parent Scope Accessed!"; 

Object.keys(data).forEach((function(Key, Index) => { 
    if(filter.type == 'parameter') { 
     Object.keys(dirArray).forEach(function(dirKey, dirIndex) => { 
     linkArray = dirArray[dirKey]; 
     if(filter.dir == 2) { //Direction filter 
      Object.keys(linkArray).forEach(function(linkKey, linkIndex) => { 
      if(filter.type != 'sub')) { 
       dataObject = linkArray[linkKey]; 

       //ERROR with scoping occurs below. Need to add parent scope. 
       console.log(this.testString); 
      } 
      }); 
     } 
     }); 
    } 
})); 

但是,這給出了一個完全新的問題,但至少IDE指示父範圍已經增加。我假設我沒有正確使用'=>'語法。有一個更好的方法嗎?

+0

剛剛Object.keys(data).forEach((Key,Index)=> { ...});'? –

+0

感謝Harry - 我需要刪除函數關鍵字。似乎錯過了功能類101。 – fila

+0

公平地說它不是101雖然;) –

回答

1

刪除該function字和定義一個函數時只使用脂肪箭頭,=>

let testString = "Parent Scope Accessed!"; 

Object.keys(data).forEach(((Key, Index)=> { 
    if(filter.type == 'parameter') { 
     Object.keys(dirArray).forEach((dirKey, dirIndex)=> { 
     linkArray = dirArray[dirKey]; 
     if(filter.dir == 2) { //Direction filter 
      Object.keys(linkArray).forEach((linkKey, linkIndex)=> { 
      if(filter.type != 'sub')) { 
       dataObject = linkArray[linkKey]; 

       //ERROR with scoping occurs below. Need to add parent scope. 
       console.log(this.testString); 
      } 
      }); 
     } 
     }); 
    } 
})); 

OR

定義根this在一個變量(var that在這種情況下):

var that = this; 
let testString = "Parent Scope Accessed!"; 

Object.keys(data).forEach((function(Key, Index) => { 
    if(filter.type == 'parameter') { 
     Object.keys(dirArray).forEach(function(dirKey, dirIndex) => { 
     linkArray = dirArray[dirKey]; 
     if(filter.dir == 2) { //Direction filter 
      Object.keys(linkArray).forEach(function(linkKey, linkIndex) => { 
      if(filter.type != 'sub')) { 
       dataObject = linkArray[linkKey]; 

       //ERROR with scoping occurs below. Need to add parent scope. 
       console.log(that.testString); //Use that instead of this here to refer to the parent scope 
      } 
      }); 
     } 
     }); 
    } 
})); 
+0

這工作完美。我知道我沒有正確使用'=>'語法。謝謝。 – fila