【发布时间】:2016-05-17 22:45:13
【问题描述】:
在性能方面什么是更好的做法: 创建原型或将方法添加到构造函数。
这是我的代码:
function DateGreeting(selector) {
this.element = document.querySelectorAll(selector)[0];
this.date = new Date();
this.hours = this.date.getHours();
this.greeting = function () {
if(this.hours <= 11) {
return "Morning";
} else if (this.hours >= 12 && this.hours <= 17) {
return "Afternoon";
} else {
return "Evening";
}
}
}
DateGreeting.prototype.append = function () {
this.element.innerHTML = this.greeting();
}
我也可以将this.greeting 变成原型,但这会提高性能还是降低性能? (或者什么都不做……)
我应该始终将方法放在原型中还是在构造函数中?
【问题讨论】:
标签: javascript oop