I have the following code:
function delay(f, ms) {
return new Proxy(f, {
apply(target, thisArg, args) {
console.log(this)
console.log(thisArg)
setTimeout(() => f.apply(thisArg, args), ms)
}
})
}
function sayHi(user) {
alert(`Hello, ${user}!`);
}
sayHi = delay(sayHi, 3000);
let container = {
f: sayHi
}
container.f("Paul")
Why is this inside the apply function equal to {apply: f} and not to the container object? this is the object before dot, isn't it?
Because that is what the specification says should happen when a proxy is used:
Or in short, the relevant things here are:
handler.applymethod fromhandler, call ittrap.Call(handler, trap, args). Whereargsis essentially, the list of arguments needed to useCallwith the original function.The
Callfrom step 8. in the specifications is executing a function, where the first argument is the function to execute, the second is the value forthis.Since the ECMAScript specification says that the second value should be
handlerand at step 1.handleris set to the [[ProxyHandler]] then the behaviour observed falls in line with the specified behaviour.