您的位置:首页 > Web前端 > JavaScript

ES6中this和箭头方法

2018-01-22 13:53 330 查看
之前写多页面应用时,一个页面就是全部,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





阅读原文
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息