this
A keyword pointing to the object a function was called on.
Example
#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)
}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
#thisMore examples
#const timer = {
seconds: 3,
start() {
const ticks = [1, 2, 3].map(() => this.seconds)
console.log(ticks)
}
}
timer.start()const user = { name: 'Emma', hello() { return 'Hello, ' + this.name } }
const hello = user.hello.bind(user)
console.log(hello())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()orobj.method.bind(obj).
Related entries
#- () => {}An arrow function: a shorter function syntax, with no own this, and an implicit return for a single expression.
- classDefines a class: a template for creating objects that share the same fields and methods.
- Object.create()Creates a new object with the given prototype.
- functionDeclares a named function: a block of code with parameters that you can call any number of times and that can return a result.
Spotted a mistake or missing an example? Write to us.