JavaScript类中如何在不同方法间共享函数?类内可声明函数吗?
首先,你当前的写法存在语法错误——JavaScript类的语法规则里,不能用function关键字定义类成员方法。下面是几种能实现“类内部复用函数”的可行方案,既保持代码整洁,又符合语法规范:
方案1:普通实例方法
把age改成类的常规实例方法,调用时通过this.age()访问,这是最直接的实现方式:
class Animal { constructor(name) { this.name = name; } cat() { console.log(`Meow! It is cat and his name is ${this.name}`); console.log(this.age('cat')); // 通过this调用类方法 } dog() { console.log(`Au! It is dog and his name is ${this.name}`); console.log(this.age('dog')); } // 去掉function关键字,直接定义类方法 age(animal){ if(animal === 'cat') return 7; if(animal === 'dog') return 5; } } const fluffy = new Animal('Fluffy'); fluffy.cat(); // 输出:Meow! It is cat and his name is Fluffy 7 const billy = new Animal('billy'); billy.dog(); // 输出:Au! It is dog and his name is billy 5
方案2:私有实例方法(避免外部访问)
如果不想让类的外部实例调用age方法,可以用ES2022支持的私有方法,方法名前加#,这样只有类内部能访问:
class Animal { constructor(name) { this.name = name; } cat() { console.log(`Meow! It is cat and his name is ${this.name}`); console.log(this.#age('cat')); // 调用私有方法 } dog() { console.log(`Au! It is dog and his name is ${this.name}`); console.log(this.#age('dog')); } // 私有方法,外部实例无法访问 #age(animal){ if(animal === 'cat') return 7; if(animal === 'dog') return 5; } } const fluffy = new Animal('Fluffy'); fluffy.cat(); // fluffy.#age('cat') // 外部调用会直接报错
方案3:静态方法(纯工具函数场景)
如果age不需要访问实例的任何属性(比如你的例子里它只接收参数返回固定值),可以把它定义成静态方法,属于类本身,调用时用Animal.age()或者this.constructor.age():
class Animal { constructor(name) { this.name = name; } cat() { console.log(`Meow! It is cat and his name is ${this.name}`); console.log(Animal.age('cat')); // 通过类直接调用静态方法 } dog() { console.log(`Au! It is dog and his name is ${this.name}`); console.log(Animal.age('dog')); } // 静态方法,属于类而非实例 static age(animal){ if(animal === 'cat') return 7; if(animal === 'dog') return 5; } } const fluffy = new Animal('Fluffy'); fluffy.cat(); // 也可直接通过类调用:Animal.age('cat') // 返回7
内容的提问来源于stack exchange,提问作者Jessica Boaventura
相关产品推荐
相关产品推荐

