Consider the following example:
const PROXY_TRAPS = [
'get',
'set',
'has',
'defineProperty',
'deleteProperty',
'getPrototypeOf',
'setPrototypeOf',
'getOwnPropertyDescriptor',
'ownKeys'
];
function Widget() {
const myTarget = { word: 'incorrect' };
const handler = Object.create(null);
for (let blockScoped = 'Hi, I\'m scoped to the \'for\' block along with my neighbours:', i = 0, trap, { length } = PROXY_TRAPS; i < length; ++i) {
const iterationScoped = 'Hi, I\'m scoped to current iteration!';
trap = PROXY_TRAPS[i];
handler[trap] = (t, ...rest) => Reflect[trap](this, ...rest); debugger; //When this function evaluates, it should search for bindings for 'trap' in its lexical environment chain untill it finds it in 'for' block and by the time it executes the value of 'trap' should be the last element of the array!
}
debugger; return new Proxy(myTarget, handler);
}
class Clock extends Widget {
constructor() {
super();
this.word = 'tok';
}
tick() {
console.log(this, this.word);
}
}
const myClock = new Clock();
myClock.tick();
If you check this code in debugger, you would notice that each property of handler
object references the correct value where I expect it to dynamically reference the corresponding binding in for
block which would me the last entry in the array.
Why is this happening?