我有一个组件,我正在初始化一个具有setter的类。这就是组件:
constructor(props) {
super(props);
this.errorLoggGateway = new ErrorLoggGateway();
}
这就是ErrorLoggGateway类:
import {fetchConvenienceWrapper} from "./fetchTools";
export class ErrorLoggGateway {
constructor() {
this.id = null;
}
set id(id) {
this.id = id;
}
loggError(error) {
return fetchConvenienceWrapper('/backend/api/logg', {
method: 'POST',
body: JSON.stringify({error, id: this.id})
});
}
}
但是,当我这样做的时候,我会得到一个错误:
RangeError: Maximum call stack size exceeded
ErrorLoggGateway.set id [as id]
C:/Users/myuser/Desktop/Projects/project/frontend/src/logic/ErrorLoggGateway.js:9
6 | }
7 |
8 | set id(id) {
> 9 | this.id = id;
| ^ 10 | }
11 | RangeError: Maximum call stack size exceeded
ErrorLoggGateway.set id [as id]
C:/Users/myuser/Desktop/Projects/project/frontend/src/logic/ErrorLoggGateway.js:9
6 | }
7 |
8 | set id(id) {
> 9 | this.id = id;
| ^ 10 | }
11 |
12 | loggError(error) {
12 | loggError(error) {
如果我更改了set方法的名称,那么它就工作了,为什么它在相同的情况下失败了?
它是set id(id)
通过this.id=
调用自己。参见console.log()
:
class Something{
set id(id){
console.log(id);
this.id=id;
}
};
new Something().id=10;
解决方案:将";私人的";变量,比如this._id
。
哦,你要求解释。CCD_ 5只是以与CCD_ 7相同的方式调用CCD_。setter就是setter,不管该属性是否从";外部";或";内部";课堂。