前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >ES6中this和箭头方法

ES6中this和箭头方法

作者头像
孙亖
发布2018-06-07 12:49:44
3730
发布2018-06-07 12:49:44
举报
文章被收录于专栏:编程直播室

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

代码语言:javascript
复制
export class ThisScope {
    txt:string = "hello this scope"
    cf1 () {
        return function() {
            this.showInfo()
        }
    }

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

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

代码语言:javascript
复制
> 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值,而不是调用时的值:

例如:

代码语言:javascript
复制
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,例如:

代码语言:javascript
复制
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

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018.01.22 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档