2016-11-16 63 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