this in Functions

کلمه کلیدی this در جاوااسکریپت به شیئی که تابع در زمان اجرا به آن تعلق دارد اشاره می‌کنه.
اما مقدار this بستگی به نحوه فراخوانی تابع (Invocation) داره.

1️⃣ this در یک تابع معمولی (Global Function)

در حالت strict mode → مقدار this برابر undefined
در حالت عادی → مقدار this برابر window (در مرورگر) یا global (در Node.js)

function showThis() { console.log(this); } showThis(); // حالت عادی: Window (در مرورگر) // حالت strict: undefined

2️⃣ this در یک متد (Method in Object)

وقتی تابع داخل یک شیء صدا زده می‌شه → this به همون شیء اشاره می‌کنه.

const person = { name: "Sara", greet: function() { console.log("Hi, I'm " + this.name); } }; person.greet(); // Hi, I'm Sara

3️⃣ this در توابع تو در تو (Nested Functions)

توابع داخلی به صورت پیش‌فرض this رو از والد به ارث نمی‌برن.

const person = { name: "Ali", greet: function() { function innerFunc() { console.log(this); // window یا undefined } innerFunc(); } }; person.greet();

📌 راه‌حل → استفاده از Arrow Function یا bind:

const person = { name: "Ali", greet: function() { const innerFunc = () => { console.log(this.name); // Ali }; innerFunc(); } }; person.greet();

4️⃣ this در Constructor Function

وقتی تابع با new صدا زده بشه → this به شیء جدید ساخته شده اشاره می‌کنه.

function Person(name) { this.name = name; } const user = new Person("Reza"); console.log(user.name); // Reza

5️⃣ this در Arrow Function

Arrow function مقدار this رو از محیط بیرونی (lexical scope) به ارث می‌بره و دیگه تغییر نمی‌کنه.

const person = { name: "Neda", greet: () => { console.log(this.name); } }; person.greet(); // undefined (this مربوط به obj نیست → مربوط به محیط global هست)

📌 پس برای متدها بهتره از function معمولی استفاده کنیم.

6️⃣ this با call, apply, bind

  • call → فراخوانی تابع با تغییر this و ارسال آرگومان‌ها جدا جدا

  • apply → مثل call ولی آرگومان‌ها در قالب آرایه

  • bind → یک نسخه جدید از تابع می‌سازه که this به شیء مورد نظر قفل شده

function greet(age) { console.log("Hi " + this.name + ", age " + age); } const person = { name: "Omid" }; greet.call(person, 25); // Hi Omid, age 25 greet.apply(person, [30]); // Hi Omid, age 30 const boundGreet = greet.bind(person, 35); boundGreet(); // Hi Omid, age 35

📌 خلاصه مهم

  • تابع معمولی → this = window/global (یا undefined در strict)

  • متد شیء → this = همان شیء

  • توابع تو در تو → this از دست می‌ره (مگر با arrow function یا bind)

  • سازنده (new) → this = شیء جدید

  • arrow function → this از محیط بیرونی میاد (lexical this)

  • call/apply/bind → کنترل دستی this