动态class variable访问需求:免固定get/set,直接访问constructor赋值变量
Solution for Dynamic Class Property Access & Filtered Data Retrieval
Great question! I've run into similar requirements when building flexible data models, and here's a straightforward, maintainable approach using JavaScript class features to meet your needs:
Core Approach
We'll use a private tracked set to keep tabs on properties explicitly set via the constructor or setData method. This lets us:
- Directly access properties on the class instance (no need for nested
this.datareferences) - Ensure
getData()only returns the properties we've intentionally tracked, ignoring any other instance properties
Implementation Code
class DynamicDataModel { // Private set to track only the properties we care about #trackedProps = new Set(); constructor(initialData = {}) { // Delegate initial data handling to setData for consistency this.setData(initialData); } setData(data) { if (typeof data !== 'object' || data === null) { throw new Error('setData requires a valid object'); } // Iterate over incoming data and attach directly to the instance for (const [key, value] of Object.entries(data)) { this[key] = value; // Mark this property as tracked this.#trackedProps.add(key); } } getData() { const filteredData = {}; // Only include properties we've tracked this.#trackedProps.forEach(key => { filteredData[key] = this[key]; }); return filteredData; } }
How It Works
- Direct Property Access: When you pass data to the constructor or
setData, each property is attached directly to the class instance. So you can doinstance.nameinstead ofinstance.data.name. - Tracked Properties: The private
#trackedPropsset keeps a record of every property we've added via the allowed methods. This ensures we don't accidentally include unrelated properties ingetData(). - Filtered Retrieval:
getData()loops through our tracked set and builds an object with only those properties, ignoring any other properties that might be added directly to the instance later.
Usage Example
// Initialize with initial data const student = new DynamicDataModel({ name: "Deep Patel", grade: 10 }); console.log(student.name); // Output: "Deep Patel" (direct access) // Add more properties later student.setData({ subject: "Computer Science", score: 98 }); console.log(student.score); // Output: 98 (direct access) // Get only tracked properties console.log(student.getData()); // Output: { name: "Deep Patel", grade: 10, subject: "Computer Science", score: 98 } // Properties added outside setData/constructor won't be included student.randomProp = "test"; console.log(student.getData()); // Still outputs the same tracked properties, no randomProp included
Bonus: Handling Updates
If you call setData with an existing property key, it will overwrite the value and remain tracked (since Set.add() doesn't duplicate entries). This works seamlessly for updates without extra code.
内容的提问来源于stack exchange,提问作者Deep Patel
相关产品推荐
相关产品推荐

