我看到的方式是,当构造函数定义类时,我可以使用 setter 来检查参数和/或将它们初始化为某些值。在我有一个计算变量的情况下,我也可以使用 getter,但我应该非常小心语句的顺序(不建议容易出错)。JavaScript 中的示例:class Point { constructor (x, y) { this.x = x.x || x // invokes the setter this.y = x.y || y } toString () { return `The point is (${this.x}, ${this.y})` // invokes the getters } set x (newX) { // I think it should be better use 'newX' as a parameter than 'x' if (newX > 100) { console.log(`The x (${newX}) value must be < 100, `, 'x set to 0') this._x = 0 // if we use 'this.x' here, we will get an error (stack overflow) return } this._x = newX } get x () { // no one but the getter and setter should know '_x' exists return this._x // it has to be coherent with the setter } set y (newY) { if (newY > 100) { console.log(`The y (${newY}) value must be < 100, `, 'y set to 0') this._y = 0 return } this._y = newY } get y () { return this._y }}