JS中的自定义数据类型

问题描述

我想用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属性,就像用[node.links.data]。

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

我不确定这是否可行,并且我很欣赏它过于繁琐,但是它确实可以清除我正在处理的代码。

解决方法

您可以定义一个返回内部数组的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

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...