我想在創建實體時自動計算并設定一個年齡。我做了一個計算并回傳年齡的函式。它有效,但我想知道是否可以在不使用全域空間的情況下在成員類中撰寫函式/方法。
class Member {
static id = 0;
constructor(firstName, lastName, birthDay) {
Member.id ;
this.id = Member.id;
this.firstName = firstName;
this.lastName = lastName;
this.birthDay = birthDay;
this.age = getAge(birthDay);
}
}
const m1 = new Member('Oliver', 'Cruz', '11/13/1990');
console.log('m1:', m1.age); // 32 (as of Nov 13rd, 2022)
const m2 = new Member('Sophia', 'Brown', '11/30/1992');
console.log('m2:', m2.age); // 29 (as of Nov 13rd, 2022)
/**
* Calculate age function
* @param {String} birthDay - ex '11/13/1990'
* @returns {Number} - age
*/
function getAge(birthDay) {
const now = new Date();
const bd = new Date(birthDay);
const diff = now - bd;
const age = new Date(diff).getFullYear() - 1970;
return age;
}
uj5u.com熱心網友回復:
您可以將其作為靜態方法添加到 Member 類中。
class Member {
static id = 0;
constructor(firstName, lastName, birthDay) {
Member.id ;
this.id = Member.id;
this.firstName = firstName;
this.lastName = lastName;
this.birthDay = birthDay;
this.age = Member.getAge(birthDay);
}
/**
* Calculate age function
* @param {String} birthDay - ex '11/13/1990'
* @returns {Number} - age
*/
static getAge = (birthDay) => {
const now = new Date();
const bd = new Date(birthDay);
const diff = now - bd;
const age = new Date(diff).getFullYear() - 1970;
return age;
}
}
const m1 = new Member('Oliver', 'Cruz', '11/13/1990');
console.log('m1:', m1.age); // 32 (as of Nov 13rd, 2022)
const m2 = new Member('Sophia', 'Brown', '11/30/1992');
console.log('m2:', m2.age); // 29 (as of Nov 13rd, 2022)
uj5u.com熱心網友回復:
class Member {
static id = 0;
static getAge(birthDay) {
const now = new Date();
const bd = new Date(birthDay);
const diff = now - bd;
const age = new Date(diff).getFullYear() - 1970;
return age;
}
constructor(firstName, lastName, birthDay) {
Member.id ;
this.id = Member.id;
this.firstName = firstName;
this.lastName = lastName;
this.birthDay = birthDay;
this.age = Member.getAge(birthDay);
}
}
?
不太確定您希望如何訪問getAge. 我將其設為靜態方法,因此您可以getAge從任何地方訪問,而無需創建單獨的 Member 實體,但這取決于您。如果你想讓它成為一個類方法,就做
//...
getAge(birthDay) {
//...
}
//...
constructor(/* args */) {
//...
this.age = this.getAge(birthDay);
//...
}
我才意識到還有另外兩個回應。L為我
uj5u.com熱心網友回復:
您可以將函式設定為類中的方法
class Member {
static id = 0;
constructor(firstName, lastName, birthDay) {
Member.id ;
this.id = Member.id;
this.firstName = firstName;
this.lastName = lastName;
this.birthDay = birthDay;
this.age = this.getAge(birthDay);
}
getAge(birthDay) {
const now = new Date();
const bd = new Date(birthDay);
const diff = now - bd;
const age = new Date(diff).getFullYear() - 1970;
return age;
}
}
const m2 = new Member('Sophia', 'Brown', '11/30/1992');
console.log('m2:', m2.age);
現在每個實體都有一個方法,而不是全域范圍內的一個函式。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/532189.html
標籤:javascript班级
