這是一個難以解決的問題,我知道它是很多程序的問題(我將在最後詳細說明這一點)。 我想在typescript中創建一個自定義的setter,但被設置的屬性的數據類型不只是一個數字,字符串,布爾它實際上是一個類對象。這工作正常 - 但如果類實例的屬性被修改,那麼setter不叫。下面是這種情況的一個例子:(Typescript)Setter不在類實例的子屬性上調用
//This class contains two properties
class Point
{
public x : number;
public y : number;
constructor(x : number, y : number) { this.x = x; this.y = 0; }
}
//How here is another class that contains a Point
//But it is private and a getter/setter is used
class PointStore
{
private _foo : Point;
public get foo() : Point { return this._foo; }
//Here is the problem, the setter is only called when the whole of foo is changed
public set foo(n : Point) { this._foo = n; console.log("Foo has been set!"); }
constructor() { this._foo = new Point(0, 0); }
}
//Use case
let bar : PointStore = new PointStore();
bar.foo = new Point(10, 10); //Logs "Foo has been set!"
bar.foo.x = 20; //Doesn't log anything
的問題是這個例子很清楚,但我只想說以下內容:
反正是有解決這個呢?因爲我已經從API,如Unity3D看到他們都選擇讓自己的「點」類只有私有成員,因此數據只能通過構造如設置:
//the 'Unity' solution
transform.position = new Vector2(10, 10); //Okay
transform.position.x = 20; //Error
但是,這是不是在所有這是一個完美的解決方案,因爲從那時起,使得'Point'類的編程變得更加困難。
如果有人有一個技巧來解決這個問題,將不勝感激。
你期待'bar.foo'的二傳手是兼容在執行'bar.foo.x'時調用? –
我知道這不會發生,但我怎樣才能使它調用setter? @NitzanTomer –
不可以。只有在爲屬性賦值時纔會調用setter,但在此處使用屬性的getter。你爲什麼想這樣做?你的目標是什麼? –