如何为生成的对象添加原型继承
Hey folks,
I’ve been grinding away at learning prototype inheritance in JavaScript lately—devoured loads of articles, sat through countless tutorial videos, and I’m finally starting to wrap my head around how it all fits together.
To solidify my understanding, I built a code example that takes an array of objects, creates a Map where each object is a key, and maps that key to an accessor object with get and set methods. These methods interact with a second map that lives in the local scope of a template factory function. Here’s the code:
function createTemplateFactory() { // 局部作用域的Map,用于存储私有值 const internalValueMap = new Map(); return { initializeObjects(objectsArray) { const objectAccessorMap = new Map(); objectsArray.forEach(targetObj => { // 为每个对象创建带get/set的访问器 objectAccessorMap.set(targetObj, { get(propertyKey) { return internalValueMap.get(`${targetObj}-${propertyKey}`); }, set(propertyKey, value) { internalValueMap.set(`${targetObj}-${propertyKey}`, value); } }); }); return objectAccessorMap; } }; } // 使用示例 const templateFactory = createTemplateFactory(); const sampleObjects = [{id: 1}, {id: 2}]; const accessorMap = templateFactory.initializeObjects(sampleObjects); // 给第一个对象设置属性 accessorMap.get(sampleObjects[0]).set('username', 'Cazineer'); // 获取该属性 console.log(accessorMap.get(sampleObjects[0]).get('username')); // 输出 "Cazineer"
Here’s my current understanding of how this ties into prototype inheritance:
- Right now, each accessor object gets its own copy of the
getandsetmethods, which is inefficient if we’re dealing with lots of objects. - To make this more aligned with prototype inheritance best practices, we can define a shared prototype for all accessor objects. This way, every accessor inherits the same
getandsetmethods instead of having duplicate copies:
// 共享的访问器原型 const AccessorPrototype = { get(propertyKey) { return this.internalMap.get(`${this.target}-${propertyKey}`); }, set(propertyKey, value) { this.internalMap.set(`${this.target}-${propertyKey}`, value); } }; function createTemplateFactory() { const internalValueMap = new Map(); return { initializeObjects(objectsArray) { const objectAccessorMap = new Map(); objectsArray.forEach(targetObj => { // 创建继承自AccessorPrototype的访问器对象 const accessor = Object.create(AccessorPrototype); // 绑定实例特定的引用 accessor.target = targetObj; accessor.internalMap = internalValueMap; objectAccessorMap.set(targetObj, accessor); }); return objectAccessorMap; } }; }
This setup uses prototype inheritance to reduce code duplication, keeps the internal value storage encapsulated via closure, and creates a clean API for interacting with the objects’ hidden properties. It’s been a great way to connect the theoretical concepts I’ve learned to a practical use case!
内容的提问来源于stack exchange,提问作者Cazineer

