[英]Adding parent scope to anonymous function - JavaScript to Angular 2
I am attempting to include an old JavaScript module within an Angular 2 project and I've hit a problem with accessing parent scope. 我试图在Angular 2项目中包含一个旧的JavaScript模块,但是在访问父范围时遇到了问题。
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);
}
});
}
});
}
}));
I've tried to do something like 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(this.testString);
}
});
}
});
}
}));
But that gives an entirely new set of issues, but at least the IDE indicates that the parent scope has been added. 但这带来了一系列全新的问题,但是至少IDE指示已添加了父作用域。 I assume I am not using the '=>' syntax correctly.
我假设我没有正确使用'=>'语法。 Is there a better way to do this?
有一个更好的方法吗?
Drop the function
word and just use the fat arrow, =>
, when defining a function 定义函数时,放下
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 要么
Define the root this
in a variable ( var that
in this case): 在变量中定义
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
}
});
}
});
}
}));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.