TypeScript 是 JavaScript 的一个超集,主要提供了类型系统和对 ES6 的支持,它由 Microsoft 开发,代码开源于 GitHub 上。
TypeScript 是 JavaScript 的类型的超集,它可以编译成纯 JavaScript。编译出来的 JavaScript 可以运行在任何浏览器上。TypeScript 编译工具可以运行在任何服务器和任何系统上。TypeScript 是开源的。
明确上面一点后,我们再来看TypeScript中的this指向问题。
下面通过例子来探讨一下TypeScript中的this指向问题:
class demo{
private str:string = "hello";
public abc(){
console.log( this.str );
}
}
编译后的js文件代码如下:
var demo = /** @class */ (function () {
function demo() {
this.str = "hello";
}
demo.prototype.abc = function () {
console.log(this.str);
};
return demo;
}());
这样生成的JS文件也并不难理解。我们再简单修改一下JS代码,
var demo = (function () {
function demo() {
this.str = "hello";
}
demo.prototype.abc = function () {
console.log(this.str);
};
return demo;
})();
var d = new demo();
d.abc();
这样运行后,可以看到打印“hello”字符。
再修改一下:
var demo = (function () {
function demo() {
this.str = "hello";
}
demo.prototype.abc = function () {
console.log( this.str);
};
demo.prototype.doing = function(callback){
callback();
}
return demo;
})();
var d = new demo();
d.abc();
d.doing(d.abc);
此时运行就会先输出一个hello
在输出一个undefined
。
这就是JS中的比较令人困惑的作用域问题了。
为避免这种问题,我们需要做如下修改
var demo = (function () {
var that;
function demo() {
this.str = "hello";
that = this;
}
demo.prototype.abc = function () {
console.log( that.str);
};
demo.prototype.doing = function(callback){
callback();
}
return demo;
})();
var d = new demo();
d.abc();
d.doing(d.abc);
TypeScript为了避免这个问题,提供了变通的解决方案:
class demo{
private str:string = "hello";
public abc(){
console.log( this.str );
}
public doing(callback){
callback();
}
public start(){
this.doing(this.abc);
}
}
上面这个代码,编译后的JS代码如下:
var demo = /** @class */ (function () {
function demo() {
this.str = "hello";
}
demo.prototype.abc = function () {
console.log(this.str);
};
demo.prototype.doing = function (callback) {
callback();
};
demo.prototype.start = function () {
this.doing(this.abc);
};
return demo;
}());
如果我们换一种写法
class demo{
private str:string = "hello";
public abc(){
console.log( this.str );
}
public doing(callback){
callback();
}
public start(){
this.doing(()=> this.abc());
}
}
这时候编译后的JS代码如下:
var demo = /** @class */ (function () {
function demo() {
this.str = "hello";
}
demo.prototype.abc = function () {
console.log(this.str);
};
demo.prototype.doing = function (callback) {
callback();
};
demo.prototype.start = function () {
var _this = this;
this.doing(function () { return _this.abc(); });
};
return demo;
}());
TypeScript是将这种作用域的问题封装到了语言层面,并为其取名“Arrow Function”。
网友评论