Prototypes & OOPmedium
Explain `this` — 4 binding rules
Describe the four rules that determine the value of `this` in JavaScript: default, implicit, explicit, and `new` binding. What does each of these log?
Asked at Google, Amazon, Meta
Answer
// Usage // Use this checklist whenever "this" is unexpected in handlers/classes. // 1. Default binding — 'this' is globalThis (undefined in strict) function show() { console.log(this) } show() // window / undefined (strict) // 2. Implicit binding — 'this' is the object before the dot const obj = { name: 'Alice', greet() { console.log(this.name) } } obj.greet() // "Alice" const fn = obj.greet fn() // undefined — lost implicit binding! // 3. Explicit binding — call / apply / bind function greet() { console.log(this.name) } greet.call({ name: 'Bob' }) // "Bob" greet.apply({ name: 'Carol'}) // "Carol" const bound = greet.bind({ name: 'Dave' }) bound() // "Dave" // 4. new binding — 'this' is the newly created object function Person(name) { this.name = name } const p = new Person('Eve') console.log(p.name) // "Eve" // Arrow functions — no own 'this', inherit from lexical scope const counter = { count: 0, start() { setInterval(() => { this.count++ // 'this' is counter, not the interval callback }, 1000) } }