我试图在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);
}
});
}
});
}
}));
我试过这样的事情:
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 :(得分: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);
}
});
}
});
}
}));
或强>
在变量中定义根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
}
});
}
});
}
}));