DEV Community

Discussion on: Rethinking JavaScript: The complete elimination and eradication of JavaScript's this.

Collapse
 
joelnet profile image
JavaScript Joel

TypeScript fixes some problems with this. Arrow functions fix some problems with this. These solutions do not fix ALL problems with this.

Consider this code that cannot be solved with TypeScript or arrow functions:

import { EventEmitter2 } from 'eventemitter2'
const events = new EventEmitter2({ wildcard: true })

events.on('button.*', function() {
  console.log('event:', this.event)
})

events.emit('button.click')
Collapse
 
ilmtitan profile image
Jim Przybylinski • Edited

You fix it with an explicitly typed this.

import { EventEmitter2 } from 'eventemitter2'
const events = new EventEmitter2({ wildcard: true })

events.on('button.*', function(this: EventEmitter2) {
  console.log('event:', this.event)
})

events.emit('button.click')