gpt4 book ai didi

javascript - Vanilla Javascript 类中的“计算属性”

转载 作者:行者123 更新时间:2023-11-28 17:04:44 25 4
gpt4 key购买 nike

计算属性功能在流行的 JS 框架(React、VueJS)中很常见,但是我们如何在 vanilla JS 中实现它?

假设给定一个具有 dateOfBirth 属性的 User 类,我们想要计算它的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()

在上面的代码中,我们通过调用一个方法来检索age值。但是,是否可以仅使用 driver.age 检索该值?

最佳答案

它是否“更好”是风格/意见的问题,但如果您想要一个属性而不是方法,您可以创建一个访问器属性,在您的情况下是一个带有getter,但没有setter

对代码进行最少的更改,您可以这样做:

function User(name, dateOfBirth) {
this.name = name;
this.dateOfBirth = dateOfBirth;

Object.defineProperty(this, "age", {
get() {
return now() - this.dateOfBirth;
}
});
}

实例:

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);

您可以使用对象初始值设定项更简洁地定义这些内容(请注意,此示例丢弃通过 new User 创建的对象,并返回一个不同的对象,该对象没有 User.原型(prototype)作为其原型(prototype)):

function User(name, dateOfBirth) {
return {
name,
dateOfBirth,
get age() {
return now() - this.dateOfBirth;
}
};
}

实例:

function now() { return Date.now(); }
function User(name, dateOfBirth) {
return {
name,
dateOfBirth,
get age() {
return now() - this.dateOfBirth;
}
};
}

var steve = new User("Steve", new Date(1990, 11, 12));
console.log(steve.age);

我还为 namedateOfBirth 使用了新的 (ES2015+) 简写属性语法

这也与 ES2015 的 class 语法兼容:

class User {
constructor(name, dateOfBirth) {
this.name = name;
this.dateOfBirth = dateOfBirth;
}
get age() {
return now() - this.dateOfBirth;
}
}

实例:

function now() { return Date.now(); }
class User {
constructor(name, dateOfBirth) {
this.name = name;
this.dateOfBirth = dateOfBirth;
}
get age() {
return now() - this.dateOfBirth;
}
}

var steve = new User("Steve", new Date(1990, 11, 12));
console.log(steve.age);

关于javascript - Vanilla Javascript 类中的“计算属性”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56144730/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com