How to use the ‘this’ Keyword in Class In Javascript
In a class in JavaScript, the ‘this’ keyword refers to the current instance of the class. It typically refers to the class that is currently being constructed by a constructor function.
Example: Explanation of Structs in JavaScript Using the ‘this’ Keyword in Class.
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
console.log(`Hello, my name is ${this.name}
and I am ${this.age} years old.`);
}
}
const john = new Person('John', 30);
john.greet();
Output
Hello, my name is John and I am 30 years old.
How to work with Structs in JavaScript ?
Structs are typically found in languages like C, C++, and similar, and they provide a way to organize related data items under one name. Typically JavaScript does not have built-in support for structs, but you can achieve similar functionality using objects. Objects in JavaScript are dynamic collections of key-value pairs, where keys are strings (or Symbols) and values can be any data.
Table of Content
- Using Objects
- Using ES6 Classes
- Using String Split()
- Using the ‘this’ Keyword in Class
- Using the ‘this’ Keyword in Object
Contact Us