I want to pass getters/setters to a function but can't. Is it even possible to do (or emulate) such thing in JS?
I tried just calling a function with getters/setters but it (pretty obviously) doesn't work, I tried "apply" and "call" and it still (somehow) doesn't work.
function foo(x, y) {
var i;
for (i = 0; i < 5; ++i)
console.log(x, y);
}
var args = [];
Object.defineProperties(args, {
"0": {
"set": function() { },
"get": Math.random
},
"1": {
"set": function() { },
"get": function() { return new Date().getMilliseconds(); }
}
});
foo.apply(this, args);
Expected 5 different results, got 5 the same instead.
The problem is that
.applyconverts your "array" into anargumentsobject, so your accessors will only be evaluated once.You can get your example working by directly passing the array to the function: