Access default getter/setter for JavaScript object Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Access default getter/setter for JavaScript object without wasting too much if your time.

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; }
    });
})();
We are here to answer your question about Access default getter/setter for JavaScript object - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji