Ban on "this"
The this keyword is one of the most confusing parts of JavaScript. Its value depends on how a function is called, not where it's defined.
The Problem
const person = {
name: 'Alice',
greet: function() {
console.log(this.name) // works: this = person
},
greetArrow: () => {
console.log(this.name) // undefined! this = global scope
}
}
const fn = person.greet
fn() // undefined! this = global/undefined (strict mode)
this Depends on Call Context
function show() {
console.log(this)
}
show() // window (or undefined in strict mode)
obj.show() // obj
show.call(obj) // obj
new show() // new instance
(x => x)(show) // inherited from outer scope
Functional Alternative
// Instead of this:
class Counter {
constructor() { this.count = 0 }
increment() { this.count++ }
}
// Use closures:
function createCounter() {
let count = 0
return {
increment: () => { count++ },
getCount: () => count
}
}
💡 At JSCamp
We discourage use of this in favor of closures and functional patterns. Arrow functions and hooks eliminate most cases where this was needed.