class CommonTools { public static watch<T>(obj: Object, name: string, callback: ($data: T) => void, init: boolean = true): void { let $value: T = obj[name] as T; Object.defineProperty(obj, name, { get() { return $value }, set($newValue) { if ($value != $newValue) { $value = $newValue; callback($value); } } }); init && callback($value); } }
class M { private k: number = 10; } window["a"] = new M(); CommonTools.watch<number>(window["a"], "k", ($data: number) => { console.log(`aaaa : ${$data}`); }, true); window["a"].k = 12; CommonTools.watch<number>(window["a"], "k", ($data: number) => { console.log(`bbb : ${$data}`); }, true); window["a"].k = 13;
此種方案很是簡單, 可是隻能由一個觀察者(這是最大的坑)ide