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爬取网页制作电子书

阅读原文

猜你喜欢

转载自tedeum.iteye.com/blog/2408418
今日推荐