this
is determined by how a function is called, not how it is defined.
Things to find this
:
- When a function is called as a method of an object,
this
refers to the object itself. - When a function is called without a context,
this
refers to the global object in non-strict mode, or toundefined
in strict mode. - When a function is called with the new keyword,
this
refers to a newly created object that inherits from the function's prototype. - When a function is called with call or apply,
this
is explicitly set to the first argument passed to call or apply. - Arrow functions do not have their own
this
value, but instead inheritthis
from the surrounding scope. - The bind method can be used to create a new function that has a specific
this
value.
Example
As a method of an object:
const person = {
name: 'John',
sayHello() {
console.log(`Hello, my name is ${this.name}!`);
}
};
person.sayHello(); // logs "Hello, my name is John!"
In a regular function:
function sayHello() {
console.log(`Hello, my name is ${this.name}!`);
}
sayHello(); // logs "Hello, my name is undefined!" in non-strict mode, or throws an error in strict mode
With the new keyword:
function Person(name) {
this.name = name;
}
const john = new Person('John');
console.log(john.name); // logs "John"
With call
or apply
:
function sayHello() {
console.log(`Hello, my name is ${this.name}!`);
}
const person = {
name: 'John'
};
sayHello.call(person); // logs "Hello, my name is John!"
In an arrow function:
const person = {
name: 'John',
greet: () => {
console.log(`Hello, my name is ${this.name}!`);
}
};
person.greet(); // logs "Hello, my name is undefined!" since arrow functions do not have their own `this` value
With bind
:
const person = {
name: 'John'
};
function sayHello() {
console.log(`Hello, my name is ${this.name}!`);
}
const sayHelloToPerson = sayHello.bind(person);
sayHelloToPerson(); // logs "Hello, my name is John!"
`
Top comments (0)