在初始化类时,使用getter和setter函数作为构造函数的一部分是一个好的实践吗?
或者直接设置变量是否更好,因为构造函数可以被认为是一种修改器?
在初始化类时,使用getter和setter函数作为构造函数的一部分是一个好的实践吗?
或者直接设置变量是否更好,因为构造函数可以被认为是一种修改器?
在构造函数中不应调用getter和setter。
构造函数用于构造定义它的特定类。它的职责是初始化字段,因为其他方法可能还未生效。
保证初始化字段的唯一方法是直接赋值。如果调用setter,则有可能被覆盖且可能执行其他操作。它可能会调用尚未初始化的子类中的方法。
如果只是从同一个类获取字段,则调用getter也是不明智的。如果该字段已在超类中声明,则您可能会认为这样做有道理;如果需要从子类中获取超类的数据,则必须调用getter(除非它是受保护的)。如果需要在构造期间从子类向超类通信数据,则应将其作为参数传递。但这是与您所描述的用例不同,而子类可能根本没有对应于getter的自己的字段。
如果有任何“特殊”的初始化代码,请将其放在单独的私有方法中,并从构造函数和setter中分别调用它。
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
}
}
this.x = x;
。 - Kartik