TypeScript 中的 this指向问题
如果你接触过TypeScript有一段时间,那么你会发现很多并非语言设计当中的“特征”。这些所谓的特征并非真正TypeScript的语法糖部分,也并非语言设计当中绝妙的点子。仔细研究TypeScript代码与编译后的 JavaScript 代码,你会发现,很多东西其实都是委曲求全的产物。
这篇文章里,我们仅来讨论关于TypeScript中 this 作用域的问题,你应该透过我的描述来了解如何去理解问题的思路。
我们来一段 TypeScript 代码:
class demo
{
private str:string = "hello";
public abc()
{
console.log( this.str );
}
}
执行 tsc 编译器,在同目录中生成一个a.js文件,内容如下:
var demo = (function () {
function demo() {
this.str = "hello";
}
demo.prototype.abc = function () {
console.log(this.str);
};
return demo;
})();
生成的JS代码并不难理解,还是先回过头来看 TypeScript 代码。
当我们创建一个类,并在类中定义了一个私有属性,在 TypeScript 中的解释为,名称为 str 的属性作用域在类中。 str 与