You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

动态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.data references)
  • 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

  1. Direct Property Access: When you pass data to the constructor or setData, each property is attached directly to the class instance. So you can do instance.name instead of instance.data.name.
  2. Tracked Properties: The private #trackedProps set keeps a record of every property we've added via the allowed methods. This ensures we don't accidentally include unrelated properties in getData().
  3. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 09:12:10