【问题标题】:Custom Datatypes in JSJS 中的自定义数据类型
【发布时间】:2020-08-30 02:03:05
【问题描述】:

我想用 JS 对自定义数据类型进行建模,想知道是否有更优雅的方法。

最终,我希望数据类型本质上表现得像一个数组,但具有一组扩展的方法来满足我的特定应用程序,可以在下面的 Links 类中看到。

class Node {
    constructor() {
        this.links = new Links();
    }
}

class Links {
    constructor(node) {
        this.data = [];  
    }
 
    initialize() {
       let initArray = [];
       let maximumIncrement = hypotheticalNodeArray.length;

        for (let i = 0; i < maximumIncrement ; i++) {
            array[i] = 0;
        }

        this.data = array;
    }
      
    // More Methods Here

}

基本上我的问题是,如果我要尝试使用 [ node.links ] 访问链接数据,则将返回整个对象,因为我希望它只是返回 data 属性,就好像数据已被访问过一样[节点.links.data]。

我知道,只需添加额外的属性并不是世界末日,但如果对象的行为类似于数组,除了具有扩展的方法集,我真的很喜欢它。

我不确定这是否可行,我很欣赏它相当迂腐,但它确实会清理我正在处理的代码。

【问题讨论】:

    标签: javascript custom-data-type


    【解决方案1】:

    您可以定义一个返回内部数组的getter

    class Node {
      constructor() {
        // renamed “_links” because we want the getter named “links”
        this._links = new Links();
      }
      get links () {
        return this._links.data;
      }
    }
    
    const node = new Node();
    node.links.map( ... ) // node.links is node._links.data
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-21
      • 1970-01-01
      • 1970-01-01
      • 2012-03-28
      • 1970-01-01
      • 2011-06-17
      • 2011-12-20
      • 2012-01-15
      相关资源
      最近更新 更多