JavaScript class methods and this keyword
The "this" keyword in JavaScript classes is not as complicated as it seems. Let's see why. But we have to understand a few things first.
• Class methods.
• Constructors
Each JavaScript class has a unique method called a constructor.
Only one constructor is allowed in each class, and its function is to define the initial state of a class.
Another property of a class is a method. A single class can have several of these. Methods define the behavior and actions of the resulting object.
A class can lack methods, but a constructor must be included otherwise, the class creates an empty object when initialized.
class Person {
constructor(name, gender){
this.name = name;
this.gender = gender;
}
}
const james = new Person ("James","Male");
console.log(james) // Person { name: 'James', gender: 'Male' };
Let's add more functionality to our object person. The resulting person should be able to greet people. Right?
class Person {
constructor(name, gender){
this.name = name;
this.gender = gender;
}
sayHi(){
console.logHi friend? I am ${this.name}. I am ${this.gender}.);
}
}
const james = new Person ("James","Male");
console.log(james); // Person { name: 'James', gender: 'Male' }
james.sayHi(); // Hi friend? I am James. I am Male
The method now allows our resulting object to be a bit dynamic. Try initializing the code with different details. Compare the output from the two instances. How different are the results? Each instance is meant to be unique and independent of all other instances.
const james = new Person ("James","Male");
const james = new Person ("Lucy","Female");
From the examples, methods:
- are defined within a class.
- Have access to class data, state, and other class methods.
- can take arguments.
- are invoked on instances/ are independent of each other.
Understanding the "this " keyword in a class
The keyword "this" in a class represents the resulting object (current instance). For example, if we console logged "this" within the constructor, like in the code below, the output is an object that holds the details of the resulting object.
// Output
Person { name: 'James', gender: 'Male' }
class Person {
constructor(name, gender){
this.name = name;
this.gender = gender;
console.log(this) // Person { name: 'James', gender: 'Male' };
}
}
const james = new Person ("James","Male");
console.log(james) // Person { name: 'James', gender: 'Male' };
}
const james = new Person ("James","Male");
console.log(james) // Person { name: 'James', gender: 'Male' };
The two console logs print out the same thing. Person { name: 'James', gender: 'Male' }
. Which is the current instance. Therefore, this refers to the created object (class instance)
When we initialize a new class, a blank object Person{}
is created, and the "this" keyword of the class is then used to assign values to the newly created object. In a constructor, it is mostly used to define where class states are stored when a class is initialized.
Example
this.name
in the example below creates a persistent instance property for each created object and stores the assigned property “name” of each instance.
const james = new Person ("James","Male"); // initializing a class
Example
this.name = name; //saves property "name" on this.name instance.
Sharing class instances between classes or between a class and a function
On mastering these basics, it is intuitive how to manipulate classes. For example, let us try to share a class instance between a class and a function.
Example
function sayGreetersName(user){
console.logyour name is ${user.name}.);
}
class Person {
constructor(name, gender){
this.name = name;
this.gender = gender;
}
checkName(){
sayGreetersName(this)
}
}
const james = new Person ("James", "Male")
james.checkName();
// Output - your name is James. Outputs the value “James” as assigned to an instance //property “name”.
Conclusion
The key takeaway from the lessons is that a class is a template for creating an object.
A constructor helps us define the initial state of our object. A class without a constructor creates an empty object.
Methods add functionality to the resulting object.
Understanding "this" keyword in a class allows us to manipulate JavaScript classes better.