README
Description
This function will allow you to set an object key with a value, without passing through any handler function such as a property setter or a proxy's handler "set" function
Exaples
You can both import the function like this
const set = require("setjsproxy");
Or like this
const { set } = require("setjsproxy");
You can use it to set normal objects
const obj = { a: 1 };
set(obj, "b", 2);
console.log(obj); // { a: 1, b: 2 }
Even on setter protected keys
const obj = { a: 1, set b(v) {}, set c(v) {} };
set(obj, "b", 2);
obj.c = 3;
console.log(obj); // { a: 1, b: 2, c: [Setter] }
And most impportantly on proxies
const obj = new Proxy({ a: 1 }, {
set: (t, k, v) => console.log(`[${ k }] = ${ v }`)
});
set(obj, "b", 2);
obj.c = 3; // [c] = 3
console.log(obj); // Proxy { a: 1, b: 2 }
How does it work?
I discovered that if you create a class that returns the instance wrapped in a proxy, and then derive inherit from said class, the class defined field of the sub class will be applied on the instance without passing through the eventual proxy's handler "set" function
class A {
constructor() {
// (If falsy throws an error in strict mode, so in classes too)
// ↓
return new Proxy(this, { set: () => true });
}
}
// (It doesn't set)
const o1 = new A();
o1.a = 1; // (Fails)
console.log(o1); // Proxy {}
class B extends A {
a = 1; // (This will be set directly)
constructor() {
super();
this.b = 2; // (Fails)
}
}
// (It sets)
const o2 = new B();
o2.c = 3; // (Fails)
console.log(o2); // Proxy { a: 1 }
Alternative
If you don't want to download the package simply paste this line of code
set=(p,k,v)=>new class extends(function(){return p}){[k]=v};