0

Are the following three ways of 'building a class' effectively the same? If not, what might be some of the more subtle or not-so-subtle differences?

class Person {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }
    get_birth_year() {
        return new Date().getFullYear() - this.age;
    }
}
let p = new Person('Bob', 33);
console.log(p.get_birth_year());

function Person(name, age) {
    this.name = name;
    this.age = age;
}
Person.prototype.get_birth_year = function() {
    return new Date().getFullYear() - this.age;
}
let p = new Person('Bob', 33);
console.log(p.get_birth_year());

function Person(name, age) {
    let person = Object.create(Person.prototype);
    person.name = name;
    person.age = age;
    return person;
}
Person.prototype.get_birth_year = function() {
    return new Date().getFullYear() - this.age;
}
let p = Person('Bob', 33);
console.log(p.get_birth_year());
David542
  • 104,438
  • 178
  • 489
  • 842
  • 1
    Conceptually yes, many subtle differences. – Jonas Wilms Feb 02 '22 at 21:09
  • Also please don't [reask questions](https://stackoverflow.com/questions/70932352/difference-between-a-function-and-class-in-es6). You've already been provided with plenty of resources on this topic. – Jonas Wilms Feb 02 '22 at 21:52

0 Answers0