Comp 110 "this"

"this"

A method is a function defined within a class. This means we call the method on an object whose type is that class. We can do a lot of fun things with methods, and we can even use them to access or change an object's properties. To do that, we must use this. The this keyword is how we refer to the current object we're in.

Let's work through an example. This example will deal with a leaf and changing its color. First, we'll see how to do this with a function:

import { print } from "introcs";
 
class Leaf {
    color: string = "green";
}
 
let changeLeafColor = (treeLeaf: Leaf, season: string): void => {
    print("original color: " + treeLeaf.color);
    if (season === "winter") {
        treeLeaf.color = "brown";
    } else if (season === "autumn" || season === "fall") {
        treeLeaf.color = "red";
    } else if (season === "spring") {
        treeLeaf.color = "bright green";
    } else {
        treeLeaf.color = "dark green";
    }
    print("new color: " + treeLeaf.color);
};
 
changeLeafColor(new Leaf(), "winter");
 
// prints:
// original color: green
// new color: brown

Next, we'll see how this would look using a method within the class definition instead of a separate function:

import { print } from "introcs";
 
class Leaf {
    color: string = "green";
 
    changeColor = (season: string): void => {
        print("original color: " + this.color);
 
        if (season === "winter") {
            this.color = "brown";
        } else if (season === "autumn" || season === "fall") {
            this.color = "red";
        } else if (season === "spring") {
            this.color = "bright green";
        } else {
            this.color = "dark green";
        }
 
        print("new color: " + this.color);
    }
}
 
let bigLeaf: Leaf = new Leaf();
bigLeaf.changeColor("winter");
 
// after the above code executes, it prints:
// original color: green
// new color: brown

In the first version of this example we used a stand-alone function and passed in a Leaf object and a season. Then, we went through the if statements and adjusted the color property of the Leaf object we passed in.

In the second version of this example, we used a method declared within the class declaration. To access the color property of the leaf so we could change it we used the this keyword to indicate that we want to change the color property of this specific leaf object that we're working in. 

The this keyword lets the method refer to the object it was called on. Every time we call a method, some things happen behind the scenes that we don't see: this is created and initialized to refer to the object the method is called on. So in the second version of our example, when we call bigLeaf.changeColor("winter");, "this" is initialized to refer to the bigLeaf object since we called the changeColor method on the bigLeaf object.