When writing multi-page applications before, one page is everything, and this is often a global object by default, but the correct understanding of this is not limited to this, especially for scripts with large and complex structures.
E.g:
export class ThisScope {
txt:string = "hello this scope"
cf1 () {
return function() {
this.showInfo()
}
}
showInfo() {
console.log(this.txt)
}
}
When we call the cf1 method, we get the error:
> Uncaught TypeError: Cannot read property 'showInfo' of undefined
at ThisScope.ts:5
at Object.defineProperty.value (main.ts:11)
at __webpack_require__ (bootstrap 87e8701…:19)
at Object.defineProperty.value (bootstrap 87e8701…:62)
at bootstrap 87e8701…:62
In the traditional form of code, callback functions are often used, and this time is easy to distinguish.
The ECMAScript 6 arrow syntax provides a facility for arrow functions to store the this value when the function is created, not when it is called:
E.g:
export class ThisScope {
txt:string = "hello this scope"
cf1() {
return function() {
this.showInfo()
}
}
cf2() {
return () => {this.showInfo()}
}
showInfo() {
console.log(this.txt)
}
}
The arrow syntax is used in cf2 above. At this time, our this is the value when the function was created.
Another way is to use bind, for example:
export class ThisScope {
txt:string = "hello this scope"
cf1() {
return function() {
this.showInfo()
}
}
cf2() {
return () => {this.showInfo()}
}
cf3() {
return function() {
this.showInfo()
}.bind(this)
}
showInfo() {
console.log(this.txt)
}
}
Above cf3, we manually bind this to the value when it was created.
More content, welcome to join the TypeScript Quick Start Chat