فهم كلمة this في JavaScript: دليل المبتدئين الشامل

كلمة this هي واحدة من أكثر المفاهيم أهمية - وأحياناً إرباكاً - في لغة JavaScript. في هذا الدرس، سنتعلم معنى this وكيف تعمل خطوة بخطوة مع أمثلة بسيطة جداً تناسب المبتدئين.

ما هي كلمة this؟

ببساطة شديدة، this هي كلمة خاصة تشير إلى الـ Object الذي ينتمي إليه الكود الحالي. لكن قيمتها تتغير حسب كيفية وأين نستخدمها.

// This is a very simple example
console.log(this); // In the browser, it will refer to the window object

أربع حالات رئيسية لتحديد قيمة this

1. this في الاستخدام العادي (Global Context)

عند استخدام this خارج أي دالة أو Object، تشير إلى الـ Object العام (Global Object).

// In the browser
console.log(this === window); // true

// In Node.js
console.log(this === global); // true

2. this داخل دوال الـ Objects (Methods)

عند استدعاء دالة كطريقة لـ Object، تشير this إلى ذلك الـ Object نفسه.

const person = {
    name: "Ahmed",
    age: 25,
    introduce: function() {
        // here this refers to the person object
        console.log(`I'm ${this.name} and I'm ${this.age} years old`);
    }
};

person.introduce(); // I'm Ahmed and I'm 25 years old

3. this في الدوال العادية

عند استخدام this داخل دالة عادية (ليست طريقة لـ Object)، تشير إلى الـ Object العام.

function sayHello() {
    console.log(this); // In browser: window
}

sayHello();

4. this في دوال السهم (Arrow Functions)

دوال السهم تتصرف بشكل مختلف! تأخذ this من Enclosing Scope لها.

const person = {
    name: "Sarah",
    regularFunction: function() {
        console.log(this.name); // Sarah (refers to person)
    },
    arrowFunction: () => {
        console.log(this.name); // undefined (refers to outer scope)
    }
};

person.regularFunction();
person.arrowFunction();

أمثلة عملية لتوضيح الفروق

المثال 1: الفرق بين الدوال العادية ودوال السهم

const car = {
    brand: "Toyota",
    startEngine: function() {
        // This is a regular function, this refers to the car object
        console.log(`Engine ${this.brand} is running`);
    },
    stopEngine: () => {
        // This is an arrow function, this is taken from the outer scope
        console.log(`Engine ${this.brand} stopped`); // Will not work correctly
    }
};

car.startEngine(); // Engine Toyota is running
car.stopEngine(); // Engine undefined stopped

المثال 2: this في معالجات الأحداث

const button = document.querySelector('button');

button.addEventListener('click', function() {
    // In event handlers, this refers to the element that triggered the event
    console.log(this); // Will refer to the button element
    this.style.backgroundColor = 'red';
});

لقيمة this ترتيب أولوية يحسم كل خلاف: new أولاً، ثم bind، ثم الاستدعاء كطريقة object.method()، ثم الاستدعاء العادي. دوال السهم خارج هذا الترتيب تماماً لأنها لا تملك this خاصاً بها، بل تقرأه من Enclosing Scope وقت التعريف، ولا يمكن تغييره بـ bind.

function show() {
  console.log(this.label);
}

const bound = show.bind({ label: "bound" });
const holder = { label: "holder", show };

holder.show();                 // holder
bound();                       // bound
show.call({ label: "call" });  // call

أشهر خطأ يقع فيه المبتدئون هو فقدان this عند تمرير طريقة كدالة callback. الدالة تُستدعى بلا Object مستقبِل، فتصبح this هي الـ Object العام أو undefined حسب الوضع:

const timer = {
  seconds: 0,
  start() {
    setTimeout(function () {
      this.seconds++;
      console.log(this.seconds);
    }, 100);
  },
};

timer.start(); // NaN instead of 1

الحل إما دالة سهم تحتفظ بـ this من start، أو bind(this)، أو تمرير الـ Object كـ Parameter بدل الاعتماد على this أصلاً. وفي Modules يعمل الكود في الوضع الصارم، لذا تحصل على TypeError: Cannot read properties of undefined بدل NaN؛ الرسالة أوضح، لكن السبب واحد.

هذا هو جوهر “Context الخاص بـ this”: ليست قيمته خاصية في الدالة، بل نتيجة طريقة استدعائها.

أما call وapply فينفذان الدالة فوراً مع Context محدد؛ call تستقبل الـ Parameters مفصولة بفواصل، وapply تستقبلها داخل Array. وbind لا تنفّذ شيئاً، بل تعيد دالة جديدة مربوطة بالـ Context، ويمكنها تثبيت بعض الـ Parameters مسبقاً:

function greet(greeting, punctuation) {
  return `${greeting} ${this.name}${punctuation}`;
}

const user = { name: "Sara" };

console.log(greet.call(user, "Hello", "!"));  // Hello Sara!
console.log(greet.apply(user, ["Hi", "?"]));  // Hi Sara?
const hello = greet.bind(user, "Hey");
console.log(hello("."));                      // Hey Sara.

داخل class تكون this هي النسخة (instance) عند استدعاء الـ Method عبرها، لكن استخراج الـ Method إلى متغير يفقدها الـ Context مرة أخرى. لذلك تحتاج في React مثلاً إلى bind أو دالة سهم عند تمرير معالج كـ Property.

نصائح مهمة للمبتدئين

  1. تذكر دائماً: this تتغير قيمتها حسب كيفية الاستدعاء
  2. في الـ Objects: استخدم الدوال العادية عندما تريد أن تشير this إلى الـ Object
  3. دوال السهم: مفيدة عندما تريد الحفاظ على قيمة this من Outer Scope
  4. تدرب كثيراً: أفضل طريقة لفهم this هي التطبيق العملي
  5. لا تفترض أن this تعني الـ Object الذي كُتبت داخله الدالة، بل الـ Object الذي استدعاها