Search code examples
javascriptarrow-functionses6-proxy

Why do I get an undefined value from the defineProperty method?


var funcSetter = {

    defineProperty: function(target, prop, descriptor) {
        if (prop) {
            let temp = descriptor.value;
            descriptor.value = temp => {
                if (temp.startsWith('_')) {
                    temp = "Default Value Attached , no Underscores allowed";
                    return temp;
                } else return temp;
            };
        }
        return true;
    }
};

let proxy_3 = new Proxy(obj_3, funcSetter);

Object.defineProperty(proxy_3, 'no', {
    value: '_Bharath',
    writable: true,
    enumerable: true,
    configurable: true
});

The issue I am facing here is that when I call the trap defineProperty, the arrow function defined under descriptor.value does not get called, hits the return true at the bottom and sets the value of the property as undefined

I am quite sure I haven't used the arrow function correctly. Could anyone guide me in the right direction?

Thank you for all the tips. Much appreciated!


Solution

  • There are two problems:

    1. You're just assigning the arrow function to descriptor.value. Not calling it.
    2. You're not actually setting the property anywhere.

    I think this should solve the problem

    var funcSetter = {
    
      defineProperty: function(target, prop, descriptor) {
        if (prop) {
          let temp = descriptor.value;
          // Use an IIFE
          descriptor.value = (temp => {
            if (temp.startsWith('_')) {
              return "Default Value Attached , no Underscores allowed";
            } else {
              return temp;
            };
          })(temp);
        }
        // Use Reflect.defineProperty to actually set the property
        return Reflect.defineProperty(target, prop, descriptor);
      }
    };
    
    let obj_3 = {};
    let proxy_3 = new Proxy(obj_3, funcSetter);
    
    Object.defineProperty(proxy_3, 'no', {
      value: '_Bharath',
      writable: true,
      enumerable: true,
      configurable: true
    });
    
    console.log(obj_3);

    Also, a MUCH simpler way to do this

    var funcSetter = {
    
      defineProperty: function(target, prop, descriptor) {
        if (prop) {
          if (descriptor.value.startsWith('_')) {
            descriptor.value = "Default Value Attached , no Underscores allowed";
          }
        }
        // Use Reflect.defineProperty to actually set the property
        return Reflect.defineProperty(target, prop, descriptor);
      }
    }
    let obj_3 = {};
    let proxy_3 = new Proxy(obj_3, funcSetter);
    
    Object.defineProperty(proxy_3, 'no', {
      value: '_Bharath',
      writable: true,
      enumerable: true,
      configurable: true
    });
    
    console.log(obj_3);