在计算性能的特点是普遍流行的JS框架(反应,VueJS),但是我们如何在香草JS实现这一点?
假设给定一个User具有dateOfBirth属性的类,我们想计算它的age,有没有比下面的代码更好的方法来执行这个任务?
function User(name, dateOfBirth) {
this.name = name;
this.dateOfBirth = dateOfBirth;
this.age = function() {
return now() - this.dateOfBirth;
}
}
var driver = new User('Steve', new Date('12 December, 1990'))
driver.age()
Run Code Online (Sandbox Code Playgroud)
在上面的代码中,我们age通过调用一个方法来检索值。但是,是否可以仅使用 来检索值driver.age?
它是否“更好”是风格/意见的问题,但是如果您想要一个属性而不是一个方法,您可以创建一个访问器属性,在您的情况下是一个带有getter但没有setter 的访问器。
对您的代码进行最少的更改,您可以这样做:
function User(name, dateOfBirth) {
this.name = name;
this.dateOfBirth = dateOfBirth;
Object.defineProperty(this, "age", {
get() {
return now() - this.dateOfBirth;
}
});
}
Run Code Online (Sandbox Code Playgroud)
现场示例:
function User(name, dateOfBirth) {
this.name = name;
this.dateOfBirth = dateOfBirth;
Object.defineProperty(this, "age", {
get() {
return now() - this.dateOfBirth;
}
});
}
Run Code Online (Sandbox Code Playgroud)
您可以使用对象初始值设定项更简洁地定义它们(请注意,此示例丢弃通过创建的对象new User并返回一个不同的对象,该对象没有User.prototype作为其原型):
function User(name, dateOfBirth) {
return {
name,
dateOfBirth,
get age() {
return now() - this.dateOfBirth;
}
};
}
Run Code Online (Sandbox Code Playgroud)
现场示例:
function now() { return Date.now(); }
function User(name, dateOfBirth) {
this.name = name;
this.dateOfBirth = dateOfBirth;
Object.defineProperty(this, "age", {
get() {
return now() - this.dateOfBirth;
}
});
}
var steve = new User("Steve", new Date(1990, 11, 12));
console.log(steve.age);Run Code Online (Sandbox Code Playgroud)
我还在那里为and使用了新的(ES2015+)速记属性语法。namedateOfBirth
这也与 ES2015 的class语法兼容:
class User {
constructor(name, dateOfBirth) {
this.name = name;
this.dateOfBirth = dateOfBirth;
}
get age() {
return now() - this.dateOfBirth;
}
}
Run Code Online (Sandbox Code Playgroud)
现场示例:
function User(name, dateOfBirth) {
return {
name,
dateOfBirth,
get age() {
return now() - this.dateOfBirth;
}
};
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1584 次 |
| 最近记录: |