I am reading You Don't Know JS: ES6 & Beyond and found some confused wording like:
We declare a
get(..)
handler as a named method on the handler object (second argument toProxy(..)
), which receives a reference to the target object (obj
), the key property name ("a"
), and the self/receiver/proxy (pobj
).
My question is, what does "receiver" mean above and where does its name come from?
It seems like if I have an object "a" with a member function "jump":
var a = { jump: function() { console.log('jump!'); } };
If I run a.jump();
then "a" is the receiver.
Is that how it works?
For people who read the same book: when you come to the Proxy First, Proxy Last section, you can add one line in the code to get a more clear picture about the context in the "get" trap:
var handlers = {
get(target, key, context) {
console.log(greeter === context); //true, this line added
return function() {
context.speak(key + "!");
};
}
},
catchall = new Proxy({}, handlers),
var greeter = {
speak(who = "someone") {
console.log("hello", who);
}
};
// setup `greeter` to fall back to `catchall`
Object.setPrototypeOf(greeter, catchall);
greeter.speak(); // hello someone
greeter.speak("world"); // hello world
greeter.everyone(); // hello everyone!
As you can see, thanks to the naming of the third argument of the "get" trap above, "context", the receiver can vary according to lexical code -- greeter.everyone();
. Please refer to Oriol's very detailed answer below for a better understanding.
receiver
comes from Message Passing style. This simply means the object that receives the message that has been passed.a
in this case receives the message to process thejump
method etc.