Are there any differences between the following two class constructions, other than the first being synactic sugar for the second?
class Number {
constructor(number) {
this.number = number;
}
toString() {
return `${this.number}`;
}
plus(that) {
return new Number(this.number + that.number);
}
static sum(c, d) {
return c.plus(d);
}
}
const c1 = new Number(2);
const c2 = new Number(3);
console.log(c1.plus(c2) + "");
console.log(Number.sum(c1,c2) + "");
class Number {
constructor(number) {
this.number = number;
}
}
// instance methods are on the prototype
Number.prototype.toString = function toString() {
return `${this.number}+${this.number}i`;
}
Number.prototype.plus = function plus(that) {
return new Number(this.number * that.number);
}
// static methods are directly on the class
Number.sum = function sum(c, d) {
return c.plus(d);
}
const c1 = new Number(2);
const c2 = new Number(3);
console.log(c1.plus(c2) + "");
console.log(Number.sum(c1,c2) + "");
Additionally, why can't I define the constructor on the class as follows (doing so just returns undefined for all the variables):
class Number {}
Number.prototype.constructor = function constructor(number) {
this.number = number;
}
console.log(new Number(2));