Reputation: 931
I have created recursive (rec) function inside setBinary method in typescript. But some reason copyColumns data is not accessible inside the recursive function in typescript but outside rec function working fine. What is wrong in my code.
while running the console.log(this.copyColummns);
It gives undefined.
copyNodeHandler ( column, node ) {
this.copyHeaders = [];
this.copyHeadersDeepCopy = [];
for ( let i = 0; i < node[ 0 ].values.length; i++ ) {
this.copyHeaders.push(node[ 0 ].values[ i ].parameterId)
}
this.copyColumns = node;
}
setBinary(rowId, vId, data) {
console.log(this.copyColumns); // working fine
let rec = function (pri, pvi) {
console.log(pri + '' + pvi);
console.log(this.copyColumns); // Not working returns undefined.
let latest = [];
if (this.copyColumns[pri]) {
this.copyColumns[pri].values[pvi].active = true;
let x = this.copyColumns[pri].values[pvi]
rec(x.pri, x.pvi)
}
};
rec(data.pri, data.pvi)
}
Upvotes: 1
Views: 64
Reputation: 1234
You are creating a new function
which creates a new scope in javascript.
You can either use arrow functions, which preserves the scope of the function it is defined in, or you need to bind(this) to your function.
Approach 1:
// arrow function
let rec = (pri, pvi) => {
console.log(pri + '' + pvi);
console.log(this.copyColumns); // Now this.copyColumns will be the same as outside this function
let latest = [];
if (this.copyColumns[pri]) {
this.copyColumns[pri].values[pvi].active = true;
let x = this.copyColumns[pri].values[pvi]
rec(x.pri, x.pvi)
}
};
Approach 2:
let rec = function (pri, pvi) {
console.log(pri + '' + pvi);
console.log(this.copyColumns); // Not working returns undefined.
let latest = [];
if (this.copyColumns[pri]) {
this.copyColumns[pri].values[pvi].active = true;
let x = this.copyColumns[pri].values[pvi]
rec(x.pri, x.pvi)
}
// bind this to the function
}.bind(this);
Upvotes: 1