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雖然;) –