我想知道方法是否有任何共同约定:
例如如果在类
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}
或者,如果有人提出更好的方法来避免在使用现有实例创建新实例时改变对象,我对替代方法同样感兴趣。
此类流畅的界面通常使用
with
作为方法名称前缀。这个约定甚至将其纳入本机 Array.prototype.with
方法中。对于您的情况,通常是 Node().withAkey(1).withBkey(1)
,但 Node().with({aKey: 1, bKey: 1})
也是可以想象的。