ES6中this和箭头方法

之前写多页面应用时,一个页面就是全部,this常常默认是全局对象,但this的正确理解不限于此,特别是大型复杂结构的脚本。
例如:

export class ThisScope {
    txt:string = "hello this scope"
    cf1 () {
        return function() {
            this.showInfo()
        }
    }

    showInfo() {
        console.log(this.txt)
    }
}

当我们调用cf1方法时,出现错误:

> 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

传统形式的代码中,回调函数常常用到,这个时候的this就容易分不清。

ECMAScript 6 箭头语法为我们提供了一个工具,箭头函数能保存函数创建时的 this值,而不是调用时的值:

例如:

export class ThisScope {
    txt:string = "hello this scope"
    cf1() {
        return function() {
            this.showInfo()
        }
    }

    cf2() {
        return () => {this.showInfo()}
    }

    showInfo() {
        console.log(this.txt)
    }
}

上面cf2使用了箭头语法,这个时候我们的this就是函数创建时的值。

另外一种方式是使用bind,例如:

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)
    }
}

上面cf3,我们手动绑定this为创建时的值。

更过内容,欢迎加入TypeScript 快速入门 的Chat

TypeScript快速入门

如何用Python爬取网页制作电子书

阅读原文

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值