我正在尝试比较类与函数构造函数。以下内容是否安全:
在类中的构造函数之外创建的任何函数等价于将函数添加为原型的函数构造函数
也会:
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];
}
}
相当于:
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];
}
答案 0 :(得分:1)
我知道的唯一区别:类必须以“严格模式”编写。
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;
}