🤯 What Is this? Where Does It Come From, Where Does It Go?

🤯 What Is this? Where Does It Come From, Where Does It Go?

A Deep Dive into JavaScript’s Most Confusing Character 😵‍💫

Everyone learning JavaScript has lived through this classic scene:

“I got it. I understand this.”
(Adds an event listener)
“Nope… I definitely don’t.”

Because this is:

Not fixed
Not global (even though it sometimes looks like it)
Not determined by where it’s written
Determined by how it’s called

In short:

this is JavaScript’s shape-shifting character 🦎


🥇 THE MOST IMPORTANT RULE

(Read this before going any further)

this is not determined by where it is written,
but by HOW it is called.

This sentence is:

  • The summary of this article
  • The secret behind this
  • The reason for 90% of this bugs

Now let’s break it down piece by piece, with lots of examples 👇


🌍 1️⃣ this in the Global Scope (Browser Version)

console.log(this);

📤 Output (Browser):

window

🧠 Why?

  • In browsers, the global object is window
  • In the global scope, thiswindow
this.alert("Hello!");

This is actually the same as:

window.alert("Hello!");

📌 Practical Tip:

  • Everything declared globally is attached to window
  • That’s why this === window

⚠️ Node.js note:
In Node, global this is {} (an empty object).
But we’re staying frontend-focused here.


🧑‍💼 2️⃣ this in Regular Functions (The First Trap ⚠️)

function showThis() {
  console.log(this);
}

showThis();

📤 Output:

window

😵‍💫 “But we’re inside a function!”

Yes, but:

  • The function is called on its own
  • It does not belong to an object

So JavaScript says:

“No owner? Fine. I’ll attach it to global.”

📌 Rule:

If a regular function is called independently,
this → global object


😬 Slightly More Confusing Example

const fn = function () {
  console.log(this);
};

fn();

Same result:

window

💡 Because:

  • How it’s defined doesn’t matter
  • How it’s called does

🧑‍🤝‍🧑 3️⃣ this as an Object Method (Where It Finally Makes Sense)

const user = {
  name: "Cansu",
  age: 28,
  sayHi() {
    console.log(this.name);
  }
};

user.sayHi();

📤 Output:

Cansu

🧠 What happened?

  • sayHi is a method
  • It’s called using .
  • this → the object to the left of the dot

So:

this === user

📌 Golden Rule #2:

If it’s called like object.method(),
this → that object


🎭 4️⃣ Same Function, Different this (Whoever Calls It Wins)

function showName() {
  console.log(this.name);
}

const user1 = { name: "Ali", showName };
const user2 = { name: "Cansu", showName };

user1.showName(); // Ali
user2.showName(); // Cansu

🤯 Same function, different results!

Because:

  • The function is the same
  • The caller is different

📌 Critical Rule:

this does not care who the function is
It cares about who called it


🏹 5️⃣ this in Arrow Functions (Very Important!)

Arrow functions:

  • Do not create their own this
  • Inherit this from the outer scope

❌ Common and Wrong Usage

const user = {
  name: "Cansu",
  sayHi: () => {
    console.log(this.name);
  }
};

user.sayHi();

📤 Output:

undefined

😱 Why?

  • Arrow function → no this
  • Outer scope → global
  • window.name → undefined

📌 Rule:

Do NOT use arrow functions as object methods


✅ Correct Arrow Function Usage

const user = {
  name: "Cansu",
  sayHi() {
    const arrow = () => {
      console.log(this.name);
    };
    arrow();
  }
};

user.sayHi();

🧠 What happened?

  • arrow inherited this from sayHi
  • sayHiuser
  • Result → 🎯

📤 Output:

Cansu


🧲 6️⃣ call, apply, bind — Forcing this

🔹 call

function greet() {
  console.log(this.name);
}

const user = { name: "Cansu" };

greet.call(user);

📤 Output:

Cansu

🧠 call:

  • You explicitly choose this
  • The function runs immediately

🔹 apply (call’s cousin)

greet.apply(user);

Difference:

  • Arguments are passed as an array

🔹 bind (The Most Professional One)

const boundGreet = greet.bind(user);

boundGreet();

🧠 bind:

  • Returns a new function
  • this is permanently fixed
  • Commonly used in events and callbacks

🖱️ 7️⃣ Event Listeners + this (Real Life!)

button.addEventListener("click", function () {
  console.log(this);
});

📤 Output:

<button>...</button>

🧠 Why?

  • Regular function
  • this → element that triggered the event

❌ If You Use an Arrow Function

button.addEventListener("click", () => {
  console.log(this);
});

📤 Output:

window

📌 In event listeners:

  • Need this → use regular function
  • Don’t need this → arrow is fine

🚨 Most Common Mistakes (Red Alert 🚨)

❌ Using arrow functions as methods
❌ Treating this like a variable
❌ Saying “it depends on where it’s defined”
❌ Guessing without console.log(this) 😄


🧩 Ultimate Cheat Sheet (Save This)

🌍 Global scope → window
🧑‍💼 Regular function → depends on how it’s called
🧑‍🤝‍🧑 Object method → the object
🏹 Arrow function → no this, inherits
🧲 call/apply/bind → you choose this
🖱️ Event listener → regular function wins


🎯 Final Words (If You’re Reading This, You’re Ready)

this is:

  • Not hard
  • Just poorly explained

Once the logic clicks, it fits together like a puzzle 🧩

Remember:

this doesn’t ask “Who am I?”
It asks “Who called me?”

Comments

No comments yet. Why don’t you start the discussion?

Bir yanıt yazın

E-posta adresiniz yayınlanmayacak. Gerekli alanlar * ile işaretlenmişlerdir