JerryMan228
JerryMan228

Reputation: 35

JS: Making sense of class vs function constructor

I am trying to compare class vs function constructor. Is it safe to say the following:
Any function created outside of the constructor in a class is equivalent to a function constructor having the function added as a prototype

so would:

class Person {
   constructor(name) {
      this.name = name;
      this.items = {}
   }
   addItem(i,value) {
        this.items[i] = this.items[i] ? this.items[i] += 1 : 1;
        return this.items[i];
   }
}

be equivalent to:

function Person2(name) {
   this.name = name;
   this.items = {}
}

Person2.prototype.addItem = function(i,value) {
    this.items[i] ? this.items[i] += 1 : 1;
    return this.items[i];
}

Upvotes: 1

Views: 46

Answers (1)

Technikhighknee
Technikhighknee

Reputation: 68

For what I know, your statement is true.

The only difference I know: A class must be written in 'strict mode'.

class Person {
    constructor(yearOfBirth) {
       this.yearOfBirth = yearOfBirth;
    }
    age() {
        // date = new Date(); This will not work
        let date = new Date();
        return date.getFullYear() - this.yearOfBirth;
    }
}
function Person2(yearOfBirth) {
    this.yearOfBirth = yearOfBirth;
}
 
Person2.prototype.age = function() {
    date = new Date(); // This will work
    return date.getFullYear() - this.yearOfBirth;
}

Upvotes: 1

Related Questions