Understanding the “This” keyword, in Javascript

this in javascript


what is “this”

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

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

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”

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 .



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