4th Street Bar Hive-Bar

Hive-Bar Powered by Hive beta-fdb5b5b

Community post

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.


Related Posts

55 upvotes $0.10

Replies (49)

Review before signing

Posting as . Signing with . Keychain permission: Posting. Hive Keychain will ask you to approve this action next.


  
Technical details

Operation fingerprint: