首页 > 解决方案 > 在递归循环中调用 setter

问题描述

我有一个 Javascript 类,它是:

class mockUser {
  constructor (
    location,
   ) {
    this.location = location;
  }

  set location (data) {
    this.location = data; // here's the problem
  }
}

但是当我尝试使用set关键字时,我会收到一个警告,说Function location recurses indefinitely and can only end by throwing an exception. 这是为什么?

我的意思是我可以

  setLocation (data) {
    this.location = data; // here's the problem
  }

但那有什么意义set呢?

我想我误解了什么。

标签: javascript

解决方案


“设置”的意思是“当某些东西试图设置这个属性时,调用这个函数”。

因此,通过在 setter 中设置位置,您正在调用 setter - 因此是递归。


推荐阅读