The question is published on by Tutorial Guruji team.
JavaScript getters and setters can be overridden for specific properties using Object.defineProperty
. Is there some way to access the default getter/setter (i.e. the function used if the getter/setter has not been overwritten)? In my custom setter I want to have special processing in some cases, but use the default processing in others. I tried:
Object.defineProperty(obj, 'foo', 'set': function(val) { if (useCustom) { doCustomProcessing(obj, 'foo', val); } else { obj['foo'] = val; } } );
Unfortunately this leads to a stack overflow since obj['foo'] = val;
causes the custom setter to be invoked. So I’d like to find a way to set the foo
property of obj
using the default setter. Is this possible?
Answer
As far as I know, a property either has a value (data property), or it has getter/setter (accessor property): it cannot have both. Use a local variable under closure, or another property, as an underlying storage for properties where you have a getter/setter defined.
For example,
(function() { var value; Object.defineProperty(obj, 'foo', { set: function(val) { if (useCustom) { value = doCustomProcessing(obj, 'foo', val); } else { value = val; } }, get: function() { return value; } }); })();