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!
There are two problems:
descriptor.value
. Not calling it.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);