Accessing Properties Inside Classes in OOP in JavaScript
Inside class methods, this will point to an object of that class:
class User {
show() {
console.log(this); // object facility subject objective entity operand obj.
}
}
This means that we can access the object's properties via this. Let's try it. Let's say our object has a property name. Let's print this property in our method:
class User {
show() {
console.log(this.name);
}
}
Let's now create an object of our class:
let user = new User;
Let's write down the property we need:
user.name = 'john';
Let's now call the method, thereby displaying the value of the property:
user.show(); // will bring out 'john'
In the object of class Employee, write the properties name and salary.
Create a method that will print the employee's name to the screen.
Create a method that will display the employee's salary.