从当前实例创建新对象但修改某些属性的方法的命名约定

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

我想知道方法是否有任何共同约定:

  1. 返回同类型对象的新实例;
  2. 使用当前实例的属性值作为默认值;
  3. 同时更改至少一个属性值。

示例

例如如果在类

foo
上调用此方法
Node
,则:

class MyNode {

  constructor({aKey, bKey}) {
    this.aKey = aKey ?? 0
    this.bKey = bKey ?? 0
  }

  /* The method I'm not sure how to name: */
  foo({aKey, bKey}) {
    return new MyNode({
      aKey: aKey ?? this.aKey, // use this instance's value as a fallback.
      bKey: bKey ?? this.bKey
    })
  }

}

const nodeA = new Node({aKey: 1}); 
console.log(nodeA) 
// {aKey: 1, bKey: 0}

const nodeB = nodeA.foo({bKey: 1});
console.log(nodeB);
// {aKey: 1, bKey: 1}

或者,如果有人提出更好的方法来避免在使用现有实例创建新实例时改变对象,我对替代方法同样感兴趣。

javascript immutability naming
1个回答
0
投票

此类流畅的界面通常使用

with
作为方法名称前缀。这个约定甚至将其纳入本机
Array.prototype.with
方法中。对于您的情况,通常是
Node().withAkey(1).withBkey(1)
,但
Node().with({aKey: 1, bKey: 1})
也是可以想象的。

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