JavaScript Basics: Reflect.apply
The method Reflect.apply
is just a better and more meaningful way to do Function.prototype.apply
. In other words, it allows you to call the given function using a specified context (this
argument) on an array of arguments. Here is an example:
let person = {
name: "John",
speak(city) {
console.log(`Hi. I am ${this.name}. I am calling from ${city}.`);
},
};
let someone = {
name: "Jack",
};
person.speak("Houston");
// Hi. I am John. I am calling from Houston.
Reflect.apply(person.speak, someone, ["Boston"]);
// Hi. I am Jack. I am calling from Boston.
person.speak.apply(someone, ["Boston"]); // the same
Function.prototype.apply.call(person.speak, someone, ["Boston"]); // the same
As I said in an earlier post, the Reflect
object gathers all functionality related to reflection in one place. This makes it possible to write neater and more readable code.
Last line is really interesting...
Function.prototype.apply.call
Was not aware it works that way. Actually:
Function.prototype.call === Function.prototype.bind.call.apply.bind.call
So it seem that
Function.prototype
functions (Function.prototype.bind
,Function.prototype.call
, etc.) do have object linkage toFunction.prototype
object. We can even access such linkage. See here:Function.prototype.apply.__proto__ === Function.prototype
That's why we can chain it deeply. Really interesting. Also was not aware of such Reflect feature. Thanks for sharing.
Thank you for your informative reply.
I didn't understood
Informative post.
Good post, thanks for sharing this post.
nice post bro
Have a nice day sir, Stay safe.
Hi I'm duma, I'm calling from Indonesia :)
sir as a new steemers i want your help by my post
Looks like i still need to learn a lot of programming :)
but many thanks for sharing it
I am not so good in javascript but this is informative 😊