Method and Property Name Conflicts in OOP in JavaScript
The names of properties and methods should not be the same, this will cause a conflict. Let's look at an example. Let's say we have the following class:
class User {
name() {
console.log('method');
}
}
Let's create an object of this class:
let user = new User;
Let's call its method while everything works:
user.name(); // works
Now let's write the data to the property of the same name, thereby erasing the method code:
user.name = 'str';
user.name(); // error mistake fault flaw fallacy miscarriage failing lapse slip trip misstep inaccuracy gaffe faux pas break stumble lapsus misdeed bungle misdoing muff clinker floater X slip-up chance-medley
To avoid such conflicts, always give methods verb names and properties noun names.
Please correct the error in the following code:
class Employee {
constructor(salary) {
this.salary = salary;
}
salary() {
return this.salary + '$';
}
}