|
| 1 | +--- |
| 2 | +title: The Two Faces of 'this' in JavaScript |
| 3 | +date: 2023-11-26 01:30:11 +0800 |
| 4 | +categories: [front-end, js] |
| 5 | +tags: [this, js] |
| 6 | +--- |
| 7 | + |
| 8 | +JavaScript's `this` is like a chameleon - its identity changes based on its surroundings. Let's dive into its true nature. |
| 9 | + |
| 10 | +## The Shape-Shifter |
| 11 | +```javascript |
| 12 | +// The global wanderer |
| 13 | +console.log(this); // Window or global |
| 14 | + |
| 15 | +// The loyal companion |
| 16 | +const ninja = { |
| 17 | + name: 'Shadow', |
| 18 | + strike() { return `${this.name} strikes!`; } |
| 19 | +}; |
| 20 | +``` |
| 21 | + |
| 22 | +## Lost in Translation |
| 23 | +The most treacherous scenarios occur during context transitions: |
| 24 | + |
| 25 | +```javascript |
| 26 | +const warrior = { |
| 27 | + name: 'Storm', |
| 28 | + attack() { |
| 29 | + setTimeout(function() { |
| 30 | + console.log(`${this.name} attacks!`); // Oops, this lost its way |
| 31 | + }, 1000); |
| 32 | + } |
| 33 | +}; |
| 34 | +``` |
| 35 | + |
| 36 | +## Arrow Functions: The Faithful Messenger |
| 37 | +```javascript |
| 38 | +const archer = { |
| 39 | + name: 'Wind', |
| 40 | + shoot() { |
| 41 | + setTimeout(() => { |
| 42 | + console.log(`${this.name} shoots!`); // Arrow keeps its promise |
| 43 | + }, 1000); |
| 44 | + } |
| 45 | +}; |
| 46 | +``` |
| 47 | + |
| 48 | +## The DOM's Special Rules |
| 49 | +```javascript |
| 50 | +button.addEventListener('click', function() { |
| 51 | + this.classList.toggle('active'); // Browser's gift - 'this' is the button |
| 52 | +}); |
| 53 | + |
| 54 | +button.addEventListener('click', () => { |
| 55 | + // Arrow function ignores the gift, keeps its own 'this' |
| 56 | + this.classList.toggle('active'); // Beware: 'this' isn't the button! |
| 57 | +}); |
| 58 | +``` |
| 59 | + |
| 60 | +## Modern Class: A Safe Haven |
| 61 | +```javascript |
| 62 | +class Knight { |
| 63 | + constructor(name) { |
| 64 | + this.name = name; |
| 65 | + this.charge = () => `${this.name} charges forward!`; // Bound forever |
| 66 | + } |
| 67 | + |
| 68 | + defend() { |
| 69 | + return `${this.name} raises shield!`; // Class method, clear context |
| 70 | + } |
| 71 | +} |
| 72 | +``` |
| 73 | + |
| 74 | +## The Golden Rules |
| 75 | +- Regular functions: `this` is decided by the caller |
| 76 | +- Arrow functions: `this` is inherited from birth |
| 77 | +- Methods: `this` is the object before the dot |
| 78 | +- Event handlers: Trust regular functions, doubt arrows |
| 79 | + |
| 80 | +Remember: context is king, but arrow functions are loyal to their birthplace. |
0 commit comments