Understanding the “This” keyword, in Javascript

Introduction
In this short article, you will learn the use of the this
keyword and it’s value in different context.
what is “this”
In JavaScript, the thing called this
is the object that "owns" the code.
The value of this
, when used in an object, is the object itself.
In a constructor function this
does not have a value. It is a substitute for the new object. The value of this
will become the new object when a new object is created.
Note that this
is not a variable. It is a keyword. You cannot change the value of this
. W3Schools
The use of this
- The
this
keyword can be used to assign value and retrieve values.
const Profile = {name: "Eric Cartman",callName() {return this.name;},};Profile.callName();
// Eric Cartman
as seen above, the name attribute of Profile was accessed in the callName method using this
.
this
can be used to create a new object property as shown below.
const Profile = {name: "Eric Cartman",addAge(age) {this.age = age;},};Profile.addAge(8);
// creates an age property for the profile object.
2. this
is used to create attribute in object constructor functions. Object constructor functions are blueprints for creating objects of the same type (having the same properties).
function Profile (name, age) {this.name = name;this.age = age;}const myProfile = new Profile('Eric', 8);
const yourProfile = new Profile('Cartman', 9);
The value of “this” in function invocation
The value of this in a function is determined by how the function is called. lets look at two case scenarios.
function name() {this.name = "john";return this.name;}name();
// name here is a global window object property
The value of this
in this context refers to the global window object.
The second scenario is a method. simply put, a method is an object property which is a function.
const profile = {age: 13,name: function () {this.name = "john";},};profile.name();
// name here is a profile object property
What will be the value of this in the code below?
const profile = {age: 13,name: function () {return this.age;},};let call = profile.name;call();
// undefined
I think you guessed right, this
now refers to the global window object.
Bind “this”
As seen above, this
refers to the global window object when a method is assigned to a new variable outside the scope of the object.
to maintain the value of this
for the declared object, the bind method is used as shown below.
const profile = {age: 13,name: function () {return this.age;},};let call = profile.name.bind(profile);call();
// 13
call now inherits the value of this
from the profile object .
Conclusion
In this short write up, you have learnt what this is and it’s usage. Let me know what you think in the comment section.
Attributions
You might need to create an account to access this https://classroom.udacity.com/courses/ud711/lessons/504843ae-ba16-4573-a859-94da7a7d1dd4/concepts/27af7aad-6d3b-483e-960d-22d3fc090dc1