Okay, so according to my knowledge, we would write a class constructor like so
class User {
constructor(name, age) {
this.name = name;
this.age = age;
}
//anything outside of constructor belong to this.prototype
getName() {
console.log(this.name);
}
getAge() {
console.log(this.age);
}
}
So instead, if I write something like this:
class User {
constructor(name, age) {
this.name = name;
this.age = age;
}
getName() {
console.log(this.name);
}
}
User.prototype.getAge = function () {
console.log(this.age);
};
It should technically be exactly the same, right? Or I am wrong? Because when I tried this which each one, I get 2 different result:
let user = new User('john', 23);
let properties = [];
for (let prop in user) {
properties.push(prop);
}
console.log(properties); //The first code result : ["name", "age"]
//The second code result : ["name", "age", "getAge"]
So what is the difference between the two?
classdefines the methods in it as non-enumerable, whereas assigning a new property directly to the prototype, creates an enumerable property (for..initerates thorugh enumerable properties only).