I need to find out the value of "name" inside on the obj object. How can I find it without function invocation?
I wanna use just obj.isActive
not obj.isActive()
let obj = {
name: "X Æ A-12 Musk",
isActive: function () {
return this.name.length > 4;
},
};
// and after a while I need to check if is active:
console.log(obj);
// {
// name: 'X Æ A-12 Musk',
// isActive: [Function: isActive] <--------- NOT COOL !
// }
If use an IFEE:
let obj = {
name: "X Æ A-12 Musk",
isActive: (function () {
return this.name.length > 4;
})(),
};
I get:
return this.name.length > 4;
^
TypeError: Cannot read properties of undefined (reading 'length')
4
Answers
If you do not want to have to call isActive as a function, you can use a getter.
It’s not clear from your question why you can do an IIFE but not a getter, but here are some other potential workarounds.
1. Use a Proxy to intercept the property accessor:
If you can’t modify the object itself you could wrap it in a Proxy, and pass the proxy to the library.
This could be generalized to invoke any getter function if it’s present on the target:
Note: I’m invoking
target[prop]()
instead ofx()
here because invoking the disassociated functionx()
has scope implications that could produce errors or unexpected results.(The same issue that makes your IIFE blow up.)2. Use
Object.defineProperty
to establish the getter.Again, it’s not clear to me why you can’t put a getter on the object literal directly, so I don’t know if this is viable either.
Similarly to ray’s answer, what about something like this:
If it helps, and you were to use it constantly, you could create a helper function:
You can create wrapper object prototyped by the original object, and define getter in the former.