TypeScript类中调用对象方法时this指向异常问题求助
解决TypeScript类方法调用时
this指向丢失的问题 这个问题我太熟悉了——当你把类的方法作为普通函数赋值给对象属性再调用时,this的指向会默认切换到调用它的对象(也就是你的validations对象),而不再指向类实例,自然就找不到isMonthValid方法了。下面给你几个实用的解决方案:
方案1:在构造函数中绑定this
这是最常用的方式,在类的构造函数里把需要外部调用的私有方法和当前类实例绑定,这样无论怎么调用这些方法,this都会牢牢指向类实例:
class YourDateValidator { constructor() { // 绑定所有需要在validations中使用的私有方法 this.checkYearMonthDate = this.checkYearMonthDate.bind(this); this.checkMonthDateYear = this.checkMonthDateYear.bind(this); this.checkDateMonthYear = this.checkDateMonthYear.bind(this); } public isValidYearMonthDate(userDateArr: any, dateFormat: string) { const dateFormatArr = dateFormat.split('-'); const validations: any = { 'YYYY-MM-DD': this.checkYearMonthDate, 'MM_DD_YYYY': this.checkMonthDateYear, 'DD_MM_YYYY': this.checkDateMonthYear }; return validations[dateFormat](dateFormatArr, userDateArr); } private checkYearMonthDate(dateArr: string[], arr: any) { return this.isMonthValid(arr[2], arr[1], arr[0]); } private checkMonthDateYear(dateArr: string[], arr: any) { // 你的校验逻辑... } private checkDateMonthYear(dateArr: string[], arr: any) { // 你的校验逻辑... } private isMonthValid(day: string, month: string, year: string) { // 你的校验逻辑... return true; } }
方案2:用箭头函数包裹方法调用
箭头函数会自动捕获当前上下文的this(也就是isValidYearMonthDate方法执行时的类实例),这样在validations对象里调用时,this不会丢失:
public isValidYearMonthDate(userDateArr: any, dateFormat: string) { const dateFormatArr = dateFormat.split('-'); const validations: any = { 'YYYY-MM-DD': (dateArr: string[], arr: any) => this.checkYearMonthDate(dateArr, arr), 'MM_DD_YYYY': (dateArr: string[], arr: any) => this.checkMonthDateYear(dateArr, arr), 'DD_MM_YYYY': (dateArr: string[], arr: any) => this.checkDateMonthYear(dateArr, arr) }; return validations[dateFormat](dateFormatArr, userDateArr); }
这种方式不需要修改构造函数,适合临时场景。
方案3:调用时用call指定this
直接在调用validations里的方法时,用call显式指定this为当前类实例,一步到位:
public isValidYearMonthDate(userDateArr: any, dateFormat: string) { const dateFormatArr = dateFormat.split('-'); const validations: any = { 'YYYY-MM-DD': this.checkYearMonthDate, 'MM_DD_YYYY': this.checkMonthDateYear, 'DD_MM_YYYY': this.checkDateMonthYear }; // 用call指定this为类实例 return validations[dateFormat].call(this, dateFormatArr, userDateArr); }
为什么你之前的_this = this无效?
如果是在isValidYearMonthDate里定义const _this = this,但直接把this.checkYearMonthDate赋值给validations的话,这个方法内部的this还是不会指向_this——因为方法本身的this指向是由调用方式决定的。只有把方法用箭头函数包裹(方案2),或者提前绑定(方案1),才能让方法内部捕获到正确的上下文。
内容的提问来源于stack exchange,提问作者kittu
相关产品推荐
相关产品推荐

