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
我很确定我没有正确使用箭头功能。任何人都能引导我朝着正确的方向前进吗?
感谢您提供的所有建议。非常感谢!
答案 0 :(得分:1)
有两个问题:
descriptor.value
。不叫它。我认为这应该可以解决问题
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);