The `this` Keyword

VIDEO

thisin Constructor Functions

In the previous section, we sawthisright inside a constructor function. Here's another example:

function Cat(name) {
 this.name = name;
 this.sayName = function () {
   console.log(`Meow! My name is ${this.name}`);
 };
}

const bailey = new Cat('Bailey');

In the aboveCat()constructor, the function thatsayNamepoints to referencesthis.name. Back in Lesson 1, we sawthisused in methods. But inCat()'s case, what exactly doesthisrefer to?

As it turns out, when invoking a constructor function with thenewoperator,thisgets set to the newly-created object! Let's check out what the newbaileyobject looks like:

{
  name: 'Bailey',
  sayName: function () {
    console.log(`Meow! My name is ${this.name}`);
  }
}

In the snippet above, notice thatthisis _outside _a constructor function (i.e., in a method). As we saw in Lesson 1, when you saythisin a method, what you're really saying is "this object" or "the object at hand." As a result, thesayName()method can usethisto access thenameproperty of that object! This makes the following method call possible:

bailey.sayName();


// 'Meow! My name is Bailey'

Note: For a refresher on how a method usesthisto access an object on which it was called, feel free to review Invoking Object Methods in Lesson 1.

When isthisAssigned?

A common misconception is thatthisrefers to the object where it is defined. This is not the case!

The value ofthisis actually not assigned to anything until an object calls the method wherethisis used. In other words, the value assigned tothisis based on the object that invokes the method wherethisis defined. Let's look at an example:

const dog = {
  bark: function () {
    console.log('Woof!');
  },
  barkTwice: function () {
    this.bark();
    this.bark();
  }
};

Let's go ahead and invoke both ofdog's methods:

dog.bark();
// Woof!

dog.barkTwice();
// Woof!
// Woof!

We know that when we calldog.bark();(ordog.barkTwice();) a variablethisgets set. Sincethiscan access the object it was called on,barkTwicecan usethisto access thedogobject, which contains thebarkmethod.

But what if we just wrotebark();instead ofthis.bark();inbarkTwice? The function would have first looked for a local variable namedbarkin the scope ofbarkTwice. Ifbarkisn't found, it would have looked further up the scope chain.

To tie things all together:this.bark();tellsbarkTwiceto look atdog-- the object that the method was called on -- to findbark.

QUESTION 1 OF 4

Time for a quick review! We explored thethiskeyword a bit in Lesson 1, so let's make sure we're on the same page before continuing.

What is true aboutthis? Select all that apply:

  • thisrefers to "this property," or "this method"

  • Usingthis, methods can access and manipulate an object's properties

  • The exact value ofthisis already set before a method is invoked

  • thisis a reserved word in JavaScript

SUBMIT: A value for this is set when a method is invoked on an object, and that value refers to that object. Since it is a reserved word, it should not be used as any variable name, function name, etc.

QUESTION 2 OF 4

Consider the following constructor function,City:

function City(name, population) {
  this.name = name;
  this.population = population;

  this.identify = function () {
    console.log(`${this.name}'s population is ${this.population}.`);
  };
}

The following is executed:

const sanFrancisco = new City('San Francisco', 870000);

What is the value ofthis?

  • City

  • Any property (such asname, orpopulation)

  • undefined, becausethismust always be inside anobject(i.e., in a method), not a constructor function

  • The newly-created object, referenced bysanFrancisco

SUBMIT: Depending on how a function is invoked, the value of this is set to a different value. We'll take a deeper dive on this very shortly!

What DoesthisGet Set To?

At this point, we've seenthisin many different contexts, such as within a method, or referenced by a constructor function. Let's now organize our thoughts and bring it all together!

There are four ways to call functions, and each way setsthisdifferently.

First, calling a constructor function with thenewkeyword setsthisto a newly-created object. Recall that creating an instance ofCatearlier had setthisto the newbaileyobject.

On the other hand, calling a function that belongs to an object (i.e., a method) setsthisto the object itself. Recall that earlier, thedogobject'sbarkTwice()method was able to access properties ofdogitself.

Third, calling a function on its own (i.e., simply invoking a regular function) will setthistowindow, which is the global object if the host environment is the browser.

function funFunction() {
  return this;
}

funFunction();
// (returns the global object, `window`)

The fourth way to call functions allows us to setthisourselves! Don't worry about this approach for now; we'll take a deep dive in the very next section.

Whew -- that was a lot ofthis! Let's compartmentalize these findings in the video below:

Video

If a constructor function is called with thenewoperator, the value ofthisis set to the newly-created object. If a method is invoked on an object,thisis set to that object itself. And if a function is simply invoked,thisis set to the global object:window.

QUESTION 3 OF 4

Consider the following object,building:

const building = {
    floor: 5,
    addFloor: function() {
        this.floor += 1;
    }
};

building.addFloor();
//???

What is the value ofthiswhenbuilding.addFloor();is executed?

  • window

  • building

  • undefined

  • addFloor()will return an error becausethis.floors += 1;cannot be resolved

SUBMIT: Recall that a method can directly access the object on which it was called. In this case, it modifies building 's floors property by incrementing its value by 1.

QUESTION 4 OF 4

Consider the following:

function myFunction() {
  console.log("What is the value of 'this'?");
}

myFunction();
// ???

WhenmyFunction();is executed, what is the value of thethiskeyword?

  • myFunction

  • undefined

  • thisdoes not get set to any value when a function is invoked

  • window

SUBMIT: When a function is invoked (i.e., as a function, rather than as a method or with the new operator), this gets set to the global object: window. This should be review from Lesson 1, but it's still important to note here as well!

Summary

Functions, objects, andthisare all interconnected. When invoking constructor functions with thenewoperator, athisvariable is set to the newly-created object. When invoking a method on an object,thisis set to that object itself. And when invoking a function in a browser environment,thisis set towindow, otherwise known as the global object.

Along with all this, there is yet one more set of ways to invoke functions: withapply(), and withcall(). Both methods share quite a few similarities, and they each allow us to specify how we want to setthis. We'll take a look at each of them in detail next!

Further Research

results matching ""

    No results matching ""