Let's say I have the following code:
class Test {
constructor(obj) {
this.obj = obj
}
change() {
Object.keys(this.obj).forEach(function(name, index) {
alert(this.obj[name])
})
}
}
objct = {
n1: 1,
n2: 2
}
var test = new Test(objct)
test.change()
However, when I run this, I get the following error:
Uncaught TypeError: Cannot read property 'obj' of undefined
I believe it means that this
is undefined inside the object keys function. How can I access this.obj
inside the Object keys and forloop?
As per this answer, I can use map
, but I need the property name and the array index
inside the forloop as well. And here's a fiddle of the code, if it may help you. Thank you!!!