In this shot, we will go over the this
keyword in JavaScript.
First, we need to understand the difference between a function and a method.
A function is a stand-alone block of code that performs a particular task.
function sayHello() {console.log("Hello")}sayHello(); // Hello
A method is also a function, but it is inside an object.
const person = {name: "John",sayHello: function(){console.log("Hello");}}person.sayHello() // Hello
this
keywordSo, if this
is inside a method, this
will refer to the object itself.
const person = {name: "John",sayHello: function(){console.log(this);}}person.sayHello();
If this
is inside a function, this
will refer to the global object, which is the window
object in Browsers and the global
object in Node.
function sayHello(){console.log(this);}sayHello();
constructor
functionWe use a constructor
function to create a blueprint of an object.
The this
keyword will refer to the created object.
The
new
keyword creates a new empty object { }.
function Person(name) {this.name = name;this.log = function(){console.log(this);}}const p1 = new Person("John");const p2 = new Person("Doe");p1.log();p2.log();
Consider the code below and try to guess what this
will refer to.
Consider the code below and try to guess what this
will refer to.
const person = {
fName: "John",
skills: ["HTML", "CSS", "JS"],
logSkills: function(){
this.skills.forEach(function(skill){
console.log(`${this.fName} can do ${skill}.`)
})
}
}
person.logSkills();
John can do HTML
John can do CSS
John can do JS
undefined can do HTML
undefined can do CSS
undefined can do JS
Try it yourself by pressing the Run button.
const person = {fName: "John",skills: ["HTML", "CSS", "JS"],logSkills: function(){this.skills.forEach(function(skill){console.log(`${this.fName} can do ${skill}.`)})}}person.logSkills();
this
is inside an objective method, and an objective method is just a regular function, so this
refers to the window
object.
That’s why we tend to use Arrow Functions as callback functions, as they do not have their own bindings to this
.
Now, when we substitute a regular callback function with an Arrow Function, we get the expected results.
const person = {fName: "John",skills: ["HTML", "CSS", "JS"],logSkills: function(){this.skills.forEach((skill)=>{console.log(`'${this.fName}' can do '${skill}'.`)})}}person.logSkills();
Free Resources