【发布时间】:2020-07-14 04:14:42
【问题描述】:
类方法、类属性是函数、类属性是箭头函数有什么区别? this 关键字在方法的不同变体中的行为是否不同?
class Greeter {
constructor() {
this.greet();
this.greet2();
this.greet3();
}
greet() {
console.log('greet1', this);
}
greet2 = () => {
console.log('greet2', this);
}
greet3 = function() {
console.log('greet3', this);
}
}
let bla = new Greeter();
这是从 TypeScript 转译后生成的 JavaScript。
var Greeter = /** @class */ (function () {
function Greeter() {
var _this = this;
this.greet2 = function () {
console.log('greet2', _this);
};
this.greet3 = function () {
console.log('greet3', this);
};
this.greet();
this.greet2();
this.greet3();
}
Greeter.prototype.greet = function () {
console.log('greet1', this);
};
return Greeter;
}());
var bla = new Greeter();
我的 TypeScript 版本是 3.4.5。
【问题讨论】:
-
当我在我的计算机上编译它时 - 没有错误 (tsc ./test.ts)。我可以获取编译好的 javascript 并在浏览器控制台中毫无问题地运行它。
-
@Combine 好吧,如果你看编译结果,差异应该很明显。
-
@Bergi 如果我的答案很清楚,我不会问这个问题。
-
@Combine 你看编译器输出了吗?可以发一下吗?
标签: javascript typescript class class-method class-fields