Your code has a few issues that need to be addressed, none of which are related to accessing this
.
Firstly, the arguments in your callback function are in the wrong order. The element should come first, followed by the index. This might be confusing if you're used to jQuery, as it uses the opposite order in its .each()
and .map()
methods.
Secondly, you're not utilizing the element correctly. Using .element
will access a property named "element" literally, rather than using the value stored in the variable element
. To access a property dynamically, you should use [element]
; check out this link for more information: Dynamically access object property using variable
const key = Object.keys(response.data)
key.forEach((element) => {
this[element] = response.data[element]
});
class MyClass {
copyProps(response) {
const key = Object.keys(response.data)
key.forEach((element) => {
this[element] = response.data[element]
});
}
}
obj = new MyClass;
obj.copyProps({
data: {
name: "MyName",
age: 10
}
});
console.log(obj);
Alternatively, you could use Object.assign()
to copy properties:
Object.assign(this, response.data);