我知道纯函数不应该改变未作为参数传入的状态,但我不知道 this
关键字是否是该规则的异常(exception)。这是我的想法的一个简单示例:
class Car {
color: string = 'red';
make: string = 'Dodge';
constructor() {}
changeMake(newMake: string): string {
this.color = 'blue'; // <-- Is this impure?
return newMake;
}
}
这不纯洁吗?为什么,或者为什么不?
最佳答案
不,您不能改变属性,因为这会改变值(对象),并且这是一个副作用。纯方法可以公开其数据,但永远不会更改它们。他们可以创建新的对象,然后它们被认为是纯粹的:
class Car {
color: string;
make: string;
constructor(color = 'red', make = 'Dodge') {
this.color = color;
this.make = make;
}
changeMake(newMake: string): Car {
return new Car(this.color, newMake);
}
}
这将创建具有新品牌的原车的副本,因此使用旧对象的每个地方仍然具有旧对象。
Java String 类就是一个很好的例子,它是纯函数式的。每个返回不同字符串的方法总是返回一个新构造的字符串。想想它是在面向对象的黄金时代构思的,这真是一个壮举。
关于javascript - 纯函数可以使用 `this` 改变其容器类内的其他属性吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54187619/