JavaScript 📜
October 2

apply() metodi

apply() metodi bilan biz metod yoza olamiz, qaysiki turli obyektlarda ishlatilina oladigan

apply() metodi call() metodiga o'xshashdir.

Asosiy farqi apply() metodida argumentlar array sifatida beriladi. call() metodida esa argumentlar birma bir beriladi.

functionName.apply(thisArg, [arg1, arg2, ...])

const person = { fullName: function(city, country) { return this.firstName + " " + this.lastName + "," + city + "," + country; } }

const person1 = { firstName:"John", lastName: "Doe" }

person.fullName.apply(person1, ["Oslo", "Norway"]);

Yana boshqa misol

function introduce(language, country) { console.log(`${this.name} speaks ${language} and lives in ${country}`); }

const person = { name: "Alice" };

introduce.apply(person, ["English", "Canada"]); // Output: Alice speaks English and lives in Canada

Misol:

function greet(title, city) { console.log(`${title} ${this.name} from ${city}`); }

const user = { name: "David" };

👉 Use apply() to make the output look like this:

Mr. David from New York

Javobi:

greet.apply(user, ["Mr", "New York"]);

🔎 Who "uses" whom in apply()?

Let’s break this down:

✅ Explanation:

  • greet is the function being called.
  • .apply(user, [...]) tells JavaScript:
"Run the greet function, and while doing that, make this inside greet point to user."

So...

The function (greet) is using the object (user) as its this context.

In short: Function uses the object, not the other way around.

🔁 To rephrase your question:

❌ “Does the object use the function?”
No — the function is using the object as its this.

🔍 Analogy:

Think of it like this:

You're borrowing someone’s clothes (function borrowing object’s properties),
not the clothes borrowing you 😄