为什么我从defineProperty方法中获取未定义的值?

时间:2017-05-29 06:26:41

标签: javascript proxy arrow-functions

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
});

我在这里遇到的问题是,当我调用陷阱defineProperty时,descriptor.value下定义的箭头函数不会被调用,在底部命中返回true并设置值属性为undefined

我很确定我没有正确使用箭头功能。任何人都能引导我朝着正确的方向前进吗?

感谢您提供的所有建议。非常感谢!

1 个答案:

答案 0 :(得分:1)

有两个问题:

  1. 您只是箭头功能分配给descriptor.value。不叫它。
  2. 您实际上并未在任何地方设置属性。
  3. 我认为这应该可以解决问题

    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);

    此外, MUCH 更简单的方法

    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);