JavaScript中如何在对象属性上直接调用方法(含嵌套场景)
解决方案
一、给字符串属性添加可直接调用的方法
原生字符串属于原始值,无法直接挂载自定义方法,但可以通过以下两种方式实现需求:
1. 修改String.prototype(全局生效)
如果希望所有字符串都能使用addM方法,可以扩展String的原型,支持带括号调用和直接访问两种形式:
带括号调用addM():
String.prototype.addM = function() { return `Mr. ${this}`; }; const obj = { person: "John Smith" }; console.log(obj.person.addM()); // 输出 "Mr. John Smith"
直接访问addM(无需括号):
用getter定义属性,访问时自动返回结果:
Object.defineProperty(String.prototype, 'addM', { get() { return `Mr. ${this}`; }, enumerable: false // 避免遍历字符串属性时出现该方法 }); const obj = { person: "John Smith" }; console.log(obj.person.addM); // 输出 "Mr. John Smith"
注意:修改全局原型可能引发命名冲突,非必要场景不推荐。
2. 自定义封装字符串对象(局部生效)
创建自定义类封装字符串,避免污染全局原型:
class WrappedString { constructor(value) { this.value = value; } // 带括号调用 addM() { return `Mr. ${this.value}`; } // 直接访问(getter) get addM() { return `Mr. ${this.value}`; } // 保留字符串的原生行为 toString() { return this.value; } } const obj = { person: new WrappedString("John Smith") }; console.log(obj.person.addM()); // "Mr. John Smith" console.log(obj.person.addM); // "Mr. John Smith" console.log(`${obj.person}`); // "John Smith"
二、嵌套对象调用fullName方法
要实现obj.person1.fullName的调用形式,核心是让每个嵌套的person对象拥有fullName属性(或方法),推荐以下方案:
1. 工厂函数创建person实例
通过工厂函数批量生成带有fullName getter的person对象,避免重复代码:
function createPerson(firstName, lastName) { return { firstName, lastName, get fullName() { return `${this.firstName} ${this.lastName}`; } }; } const obj = { person1: createPerson("John", "Smith"), person2: createPerson("Jane", "Doe") }; console.log(obj.person1.fullName); // "John Smith" console.log(obj.person2.fullName); // "Jane Doe"
2. 使用ES6类(更规范的面向对象方式)
用类定义Person结构,每个实例自动继承fullName getter:
class Person { constructor(firstName, lastName) { this.firstName = firstName; this.lastName = lastName; } get fullName() { return `${this.firstName} ${this.lastName}`; } } const obj = { person1: new Person("John", "Smith"), person2: new Person("Jane", "Doe") }; console.log(obj.person1.fullName); // "John Smith"
3. 手动给每个嵌套对象添加getter(简单场景)
如果person数量少,可直接给每个对象添加fullName getter:
const obj = { person1: { firstName: "John", lastName: "Smith", get fullName() { return `${this.firstName} ${this.lastName}`; } }, person2: { firstName: "Jane", lastName: "Doe", get fullName() { return `${this.firstName} ${this.lastName}`; } } }; console.log(obj.person1.fullName); // "John Smith"
内容的提问来源于stack exchange,提问作者Peter SH
相关产品推荐
相关产品推荐

