I realize my question's title may be worded weirdly, so I apologize up front. To be clear, I am referring to this:
var IIFE = (function () {
var a = Symbol("a");
function IIFE() {
this["a"] = null;
}
IIFE.prototype = {
get a() { return this[a]; },
set a(n) { this[a] = n; }
}
return IIFE;
}());
var iife = new IIFE;
I want to dynamically add 'b' & 'c' using an array:
var arrProps = ['b','c'];
to an instance of IIFE. I don't care how it gets done, so as long as the values specified within arrProps
can be accessed & assigned the same as you would with 'a' inside the instance, outside the instance, and within prototype get/set. An example of using 'b' would be:
this["b"] = value;
iife.b = value;
this[b] = value;
As far as the get/set internals go, there is nothing more than just getting the value and setting value.
Any help would be very much appreciated.
Instead of using a Symbol, have the function return a Proxy instead, and you can use its get
and set
traps to check for accesses/assignments to arbitrary properties:
const proxy = new Proxy({}, { get(obj, prop) { console.log('getting'); return obj[prop]; }, set(obj, prop, newVal) { console.log('setting'); return obj[prop] = newVal; }, }); proxy.a = 'aVal'; console.log(proxy.a); proxy.b= 'bVal'; proxy.c = 'cVal'; proxy.a = 'anotherAVal';
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.