是的,可以在使用var分配的TypeScript中實現對'this'的詞彙捕獲,但我不會推薦它。當你理解JavaScript這個機制實際上如何工作時,詞彙捕捉'this'是完全不必要的。
的「本」在打字稿通常是用箭頭功能實現的,但儘管如此,這裏有一個樣本打字稿類,說明實現的所有三種不同的方式,你想要什麼詞彙捕獲:
class Car {
speed: number
constructor() {
this.speed = 0
}
// lexical capture of 'this' with var
increaseSpeed1() {
var _car = this
setInterval(function() {
_car.speed += 2
}, 32)
}
// lexical capture of 'this' with arrow function
// (a pretty way of doing the same as above)
increaseSpeed2() {
setInterval(() => {
this.speed += 2
}, 32)
}
// binding to 'this'
// (I consider this the proper way, when you really understand how 'this' works)
increaseSpeed3() {
setInterval(function() {
this.speed += 2
}.bind(this), 32)
}
}
在increaseSpeed1
,_car對象不能在setInterval的回調中解析(即使回調確實有它自己的'this'值),所以引擎會查找下一個可用範圍,並在_car範圍內找到所需的聲明和值_car增加Speed1功能。在這裏,_car已經從詞彙上捕獲了Car類的'this'值。
在使用箭頭函數的increaseSpeed2
中,setInterval回調的'this'值基本上被拋出,並且increaseSpeed2函數的作用域'this'的值(與'this'相同Car類的值)在詞彙上被setInterval回調採用。
在increaseSpeed3
,我們綁定到汽車類的「本」的價值。綁定到car類的'this'值可以從setInterval回調中創建一個新的函數,該函數將在Car類的'this'的上下文中執行。就像我在代碼示例中所說的那樣,這是在尊重JavaScript'this'機制如何工作的同時,實現您想要的最合適的方式。
還要注意的是,你應該決定箭頭的功能是你的喜好,你可以使increaseSpeed2
功能更加緊湊通過移除回調函數體周圍的大括號(因爲代碼只有一行):
increaseSpeed2() {
setInterval(() => this.speed += 2, 32)
}
快樂編碼。希望這可以幫助!