'this' is a property of an execution context
In non–strict mode, 'this' refers to the Object that is executing the current function.
In strict mode, 'this' can be any value.
The value of 'this' depends on the context in which it is used. Let's dive in!
Global Context
When 'this' is used globally, (meaning it is not within a method or function) it automatically refers to the window object.
console.log(this); // {window Object}
Function Context
Regular Function Context
'this' within a regular function that is not part of an Object also refers to the window Object as shown below
const showThis = () => {
console.log(this); // {window Object}
}
//In strict mode, however, if the value of this is not
// set when entering an execution context, it remains as undefined, as shown in the following example:
const showThis = () => {
'use strict'; // see strict mode
console.log(this); // undefined
}
Constructor Function Context
When using the constructor function to create a new object, the 'new' operator creates an object and points 'this' to the newly created object.
function Series (title) {
this.title = title;
console.log (this); // {Newly created Object}
}
const v = new Series ('The Office'); // Create new Object using constructor function.
Method Context
A method is a function that is part of an Object.
'this' within a method refers to its parent Object.
const things = {
roses: 'red',
sky: 'blue',
snow:'white',
showColor(){
console.log(this); // {things Object}
console.log(this.roses); // 'red'
}
};
A callback function within a method would refer to the window Object unless a 'this' argument aka thisArg is provided.
The thisArg is an optional value to use as 'this' when executing callback function. Take a look at how this works using the forEach array method.
Syntax
// arr.forEach(callback(currentValue) {
// // execute something
// }, [thisArg]);
const random = {
title: 'Primary',
colours: ['red'],
showColours ()){
this.colours.forEach(colour => {
console.log(this.heading, colour) // Rosy red
}, { heading: 'Rosy' }) // optional 'this' argument
}
};
That's all folks, see you next week!
Top comments (0)