Struggling with understanding JavaScript/TypeScript closures even after reviewing multiple examples online.
Here's the code causing me issues:
let obj = {
message: '222',
printMessage: function() {
return this.message
},
}
console.log(obj.printMessage()); // 222
let func = obj.printMessage;
console.log(func()); // undefined
Encountering the error
Cannot read property 'message' of undefined
when running this code.
Aware that directly calling obj.printMessage()
works but looking to return the printMessage
function as a variable for use in another function.
Suspecting the issue lies in closure, seeking guidance on tackling it.
Appreciate any insight shared.
===========================================
Update:
Managed to resolve the problem through further code experimentation.
Here's the solution implemented:
let obj = {
message: '222',
printMessage: function() {
return this.message
},
getPrintMessage: function () {
return () => this.printMessage()
}
}
console.log(obj.printMessage()); // 222
let func = obj.getPrintMessage();
console.log(func());
Incorporated an additional function to return an anonymous function calling this.printMessage()
, enabling access from outside the object.
Grateful for all contributions and support provided.