如何在JavaScript函数中读取TypeScript类的成员?
I see you're tackling the classic this context issue when working with nested functions in TypeScript. Let's break down what's going on and how to handle it cleanly.
First, here's your code formatted for clarity:
export class CustomToast implements OnInit { toastTypeGroup: string; message: string; title: string; showDuration = "300"; constructor(_toastTypeGroup: string, _message:string, _title: string ){ this.toastTypeGroup = _toastTypeGroup; this.message = _message; this.title = _title; } ngOnInit() { // Your initial solution var _this = this; console.log(this.showDuration); var ToastrDemo = function () { var toastr: any = (<any>window).toastr; var k, m = -1, f = 0; var t = ... // Rest of your function logic // Here you'd use _this.showDuration instead of this.showDuration }; } }
Why Your Current Solution Works
When you declare a regular function() {}, it creates its own this context that doesn't point to your class instance. By assigning var _this = this; outside the nested function, you're capturing the class's this reference so you can access its members inside the function. This is a tried-and-true workaround for older JS/TS code.
A Cleaner Modern Alternative: Arrow Functions
Since TypeScript supports ES6 features, you can use arrow functions to avoid manually capturing this. Arrow functions inherit the lexical this from their surrounding scope—meaning they'll automatically reference your CustomToast instance without extra work.
Here's how to rewrite your code for cleaner, more maintainable code:
export class CustomToast implements OnInit { toastTypeGroup: string; message: string; title: string; showDuration = "300"; constructor(_toastTypeGroup: string, _message:string, _title: string ){ this.toastTypeGroup = _toastTypeGroup; this.message = _message; this.title = _title; } ngOnInit() { console.log(this.showDuration); // Replace regular function with arrow function const ToastrDemo = () => { const toastr: any = (<any>window).toastr; let k, m = -1, f = 0; let t = ... // Rest of your function logic // Now you can directly use this.showDuration here! console.log(this.showDuration); }; } }
Quick Additional Tips
- I swapped
varforconst/letto use modern block scoping, which helps avoid accidental variable leaks. - If
showDurationis meant to be a numeric value (since it represents a duration), consider typing it asnumberinstead ofstring:showDuration = 300;—just make sure any code using it expects a number instead of a string.
内容的提问来源于stack exchange,提问作者antony

