在jquery回調(diào)中調(diào)用時,TypeScript“this”作用域問題我不確定在TypeScript中處理“this”范圍的最佳方法。這是我轉(zhuǎn)換為TypeScript的代碼中常見模式的示例:class DemonstrateScopingProblems { private status = "blah"; public run() { alert(this.status); }}var thisTest = new DemonstrateScopingProblems();// works as expected, displays "blah":thisTest.run(); // doesn't work; this is scoped to be the document so this.status is undefined:$(document).ready(thisTest.run); 現(xiàn)在,我可以將呼叫改為......$(document).ready(thisTest.run.bind(thisTest));......確實有效。但它有點可怕。這意味著代碼可以在某些情況下編譯和工作正常,但如果我們忘記綁定范圍,它將會中斷。我想在類中做一個方法,這樣在使用類時我們不需要擔心“this”的作用范圍。有什么建議?
3 回答

千巷貓影
TA貢獻1829條經(jīng)驗 獲得超7個贊
另一種解決方案需要一些初始設(shè)置,但是憑借其無形的光,字面上的單字語法得到回報,使用方法裝飾器通過getter JIT綁定方法。
我已經(jīng)在GitHub上創(chuàng)建了一個repo來展示這個想法的實現(xiàn)(它有點冗長以適應(yīng)其40行代碼的答案,包括注釋),你可以簡單地使用:
class DemonstrateScopingProblems { private status = "blah"; @bound public run() { alert(this.status); }}
我還沒有在任何地方看到這個,但它完美無瑕。此外,這種方法沒有明顯的缺點:這個裝飾器的實現(xiàn) - 包括對運行時類型安全的一些類型檢查 - 是微不足道和直接的,并且在初始方法調(diào)用之后基本上沒有開銷。
關(guān)鍵部分是在類原型上定義以下getter,它在第一次調(diào)用之前立即執(zhí)行:
get: function () { // Create bound override on object instance. This will hide the original method on the prototype, and instead yield a bound version from the // instance itself. The original method will no longer be accessible. Inside a getter, 'this' will refer to the instance. var instance = this; Object.defineProperty(instance, propKey.toString(), { value: function () { // This is effectively a lightweight bind() that skips many (here unnecessary) checks found in native implementations. return originalMethod.apply(instance, arguments); } }); // The first invocation (per instance) will return the bound method from here. Subsequent calls will never reach this point, due to the way // JavaScript runtimes look up properties on objects; the bound method, defined on the instance, will effectively hide it. return instance[propKey];}
這個想法也可以更進一步,通過在類裝飾器中執(zhí)行此操作,迭代方法并在一次傳遞中為每個方法定義上述屬性描述符。
- 3 回答
- 0 關(guān)注
- 852 瀏覽
添加回答
舉報
0/150
提交
取消