私有 props 在子类方法范围内的类中返回未修改或丢失的值

问题描述 投票:0回答:1

所以,我有两个类服务类和实体类,带有私有构造函数和静态异步方法,用于创建类的新实例。我的服务类创建并调用新的实体类实例并使用其属性对其进行修改。

示例 |这不是

NEST.JS
代码:

class Service {
   run() {
     const entity = Entity.createNewEntity(args);

     await entity.methodMother();

     const getMyProps1Back = entity.props1();

     // is [ ] empty array, not modified after methodChild
     console.log(getMyProps1Back);

   }
}

我的实体的每个方法都覆盖了来自 npm 的

bind
装饰器:bind-decorator 模块

class Entity {
  this.props1! Array<Record<Type>>;
  this.props2 = new Map([]);


  private constructor(someArgs: any) {
     // some stuff
     this.props1 = [];  
  }

  get getProps1() {
    return this.props1;
  }

  static async createNewEntity() {
     const entity = new Entity();
     // blah-blah work here
     return entity;
  }

  @bind
  public async methodMother() {
    this.props1.push({ some: stuff });

    // 

    this.methodChild();
    // method logic
  }

  @bind
  private methodChild() {
     // adding more elements, or overwriting the array
     this.props1 = [test1, test2, test3];
  }
}

所以我这里的问题是解释为什么在

methodChild
内调用
methodMother
期间会丢失上下文,以及我的
getter
如何返回未修改的
props1
数组?

## 它是如何工作的,我应该怎样做才能避免它?

像这样传递一个类似数组的参数并将其返回?或者其他什么,比如让他们匿名?

  @bind
  private methodChild(props1 : Array<OfProps1>) {
     // adding more elements, or overwriting the array
     props1 = [test1, test2, test3];

     return arg;
  }
javascript typescript this solid-principles
1个回答
0
投票

您发送的代码在没有

@bind
装饰器的情况下似乎可以正常工作(经过一些清理):

type KeyType = any
type ValueType = any

class Entity {
  props1!: Record<KeyType, ValueType>[];
  props2 = new Map([]);


  private constructor() {
    // some stuff
    this.props1 = [];
  }

  getProps1() { // <-- NOTE: Removed the `get` from here
    return this.props1;
  }

  static async createNewEntity() {
    const entity = new Entity();
    // blah-blah work here
    return entity;
  }

  public async methodMother() {
    this.props1.push({ some: 'stuff' });

    this.methodChild();
  }

  private methodChild() {
    this.props1 = [
      ...this.props1,// existing values

      { some: 'other stuff' },
      { evenMore: 'other stuff' },
      { andMore: 'other stuff' }
    ]
  }
}

当你运行它时:

class Service {
  async run() {
    const entity = await Entity.createNewEntity();

    await entity.methodMother();

    const getMyProps1Back = entity.getProps1();

    console.log(getMyProps1Back);
  }
}

你会得到一个不错的输出:

[
  {
    some: "stuff",
  },
  {
    some: "other stuff",
  },
  {
    evenMore: "other stuff",
  },
  {
    andMore: "other stuff",
  }
]

这是基于您提供的代码。

© www.soinside.com 2019 - 2024. All rights reserved.