Skip to content

โšก JS Prototypes & this Binding

  • In Javascript:
    • Every object has a hidden property called [[Prototype]] which can be accessed using _proto_
    • When you access a property on an object, JS looks:
        1. In the object itself.
        1. If not found, it delegates to its prototype chain.
    • Eg:
      const person = {name: "Sonam"}
      console.log(person.toString()) // [object object]
    • โœ… toString is not defined in person, but JS finds it in Object.prototype.
function Person (name){
this.name = name
}
Person.prototype.sayHello = function (){
return `Hello from : ${this.name}`
}
const user = new Person('Sonam')
console.log(user.sayHello())
  • โœ… sayHello is not copied to each object โ€” itโ€™s stored in prototype and shared.

โ€œPrototypes allow objects to share methods without duplicating them in memory.โ€

  • this depends on how a function is called ,not where itโ€™s defined.
  • Eg:
Case 1: Global Scope
console.log(this) // In browser โ†’ window, in Node โ†’ {}
Case 2 : Inside a method
const obj = {
a: 10,
getData: (){
console.log(this.a)
}
}
obj.getData() // 10
โœ… this refers to the object calling the method (obj).
Case 3: Lost this (Common Pitfall)
const obj = {
a: 10,
getData: (){
console.log(this.a)
}
}
const fn = obj.getData
fn(); // undefined (in strict mode)
โœ… Because now fn is just a function, not called on obj.
Case 4: this in Arrow Functions
const obj = {
name: "Sonam",
greet: () => {
console.log(this.name);
}
};
obj.greet(); // โŒ undefined
โœ… Arrow functions do not bind their own this.
They inherit this from the lexical scope (where they were created).
AspectRegular Function (function)Arrow Function (=>)
Own this?โœ… Yes, this depends on how the function is called.โŒ No, arrow functions do not bind this; they use this from the enclosing lexical scope.
Default this in global scope (non-strict)window (in browsers)window (same as lexical scope)
Default this in strict modeundefinedInherits from enclosing scope
Inside an object methodRefers to the object that called itโŒ Refers to outer scope (usually window/undefined)
In a class methodRefers to the instanceโŒ Still lexical this (not the instance unless wrapped)
Can use bind / call / apply?โœ… YesโŒ No effect โ€” arrow functions ignore binding
Best use caseObject methods, class methods, dynamic thisCallbacks, promises, event listeners (when you want to inherit surrounding this)
  • Regular function โ†’ this is dynamic (depends on call).
  • Arrow function โ†’ this is lexical (depends on where defined).
  • Prototype โ†’ Object inheritance mechanism.
  • this โ†’ Value depends on call site, not definition.
  • Arrow functions โ†’ no own this, use lexical scope.
  • bind/call/apply โ†’ Explicitly control this.