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指示父范围已经增加。我假设我没有正确使用'=>'语法。有一个更好的方法吗?
刚刚Object.keys(data).forEach((Key,Index)=> { ...});'? –
感谢Harry - 我需要删除函数关键字。似乎错过了功能类101。 – fila
公平地说它不是101虽然;) –