Reputation: 35
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
Reputation: 68
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