如何在创建Member类实例时内置age计算方法,不使用全局空间
解决方案:将年龄计算函数整合到Member类内部
下面提供几种可行的方案,既能把getAge函数纳入类内部避免全局空间污染,又能保持实例创建时自动计算年龄的逻辑:
方案1:使用静态方法(推荐)
因为getAge仅处理传入的生日参数,不需要访问实例属性,适合定义为类的静态方法,属于类本身而非实例:
class Member { static id = 0; // 将getAge转为类的静态方法 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); } } 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)
方案2:使用私有实例方法(ES2022+)
如果后续需要让年龄计算逻辑访问实例的其他属性,可以用私有方法封装,外部无法访问,彻底隔离内部实现:
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 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)
方案3:构造函数内部定义函数(不推荐)
这种方式会为每个实例创建独立的函数副本,浪费内存,仅适合临时简单场景:
class Member { static id = 0; constructor(firstName, lastName, birthDay) { Member.id++; this.id = Member.id; this.firstName = firstName; this.lastName = lastName; this.birthDay = birthDay; // 构造函数内部定义计算函数 const getAge = (birthDay) => { const now = new Date(); const bd = new Date(birthDay); const diff = now - bd; const age = new Date(diff).getFullYear() - 1970; return age; }; this.age = getAge(birthDay); } }
内容的提问来源于stack exchange,提问作者Miu
相关产品推荐
相关产品推荐

