this

A keyword pointing to the object a function was called on.

On this page

Example

#
JavaScript
const course = {
  title: 'JavaScript course',
  describe() {
    return `This is the ${this.title}`
  }
}

console.log(course.describe())

const describe = course.describe
try {
  describe()
} catch (error) {
  console.log(error.name)
}
Console
This is the JavaScript course
TypeError

Definition and usage

#

The value of this depends on how a function was called, not where it was defined. In a method called as object.method(), this points to object. In a plain function call in strict mode, this is undefined.

Arrow functions don’t have their own this. They pick it up from where they were written. That’s why they work great as callbacks inside methods, but aren’t suited to being methods themselves.

The most common mistake is "losing" this when passing a method along, for example as an event handler. An arrow function, or method.bind(object), fixes it.

Syntax

#
Syntax
this

More examples

#
An arrow function inherits this from its surroundings
JavaScript
const timer = {
  seconds: 3,
  start() {
    const ticks = [1, 2, 3].map(() => this.seconds)
    console.log(ticks)
  }
}

timer.start()
Console
[3, 3, 3]
Pinning this with bind()
JavaScript
const user = { name: 'Emma', hello() { return 'Hello, ' + this.name } }
const hello = user.hello.bind(user)

console.log(hello())
Console
Hello, Emma

Browser support

#

Widely available

Works in all modern browsers, phones included. You can use it without worry.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • Write object methods with the regular method() {} syntax, and callbacks inside them as arrow functions.
  • When passing a method as an event handler, use () => obj.method() or obj.method.bind(obj).

Related entries

#

Spotted a mistake or missing an example? Write to us.