你会如何推荐我将此 JavaScript 转换为 TypeScript?
JAVASCRIPT:
function MyClass() {
var self = this,
var1 = "abc",
var2 = "xyz";
// Public
self.method1 = function () {
return "something " + self.var1;
};
self.method2 = function (parm1) {
var x = self.method1();
return x + " something";
};
// Private
function func1(parm1, parm2) {
return parm1 + parm2;
}
}
这就是我想在 TypeScript 中做的事情,或者至少是我希望如何编写它:
module MyNamespace {
export class MyClass {
private var1: string = "abc";
private var2: string = "xyz";
constructor() {
}
// Public
public method1() {
return "something " + self.var1;
}
public method2(parm1) {
var x = this.method1();
return x + " something";
}
// Private
private func1(parm1, parm2) {
return parm1 + parm2;
}
}
}
但是生成的 JavaScript 将所有内容都放在原型上,我将遇到一些“this”范围问题:
var MyNamespace;
(function (MyNamespace) {
var MyClass = (function () {
function MyClass() {
this.var1 = "abc";
this.var2 = "xyz";
}
// Public
MyClass.prototype.method1 = function () {
return "something " + this.var1;
};
MyClass.prototype.method2 = function (parm1) {
var x = this.method1();
return x + " something";
};
// Private
MyClass.prototype.func1 = function (parm1, parm2) {
return parm1 + parm2;
};
return MyClass;
})();
MyNamespace.MyClass = MyClass;
})(MyNamespace || (MyNamespace = {}))
我知道我可以在构造函数中声明方法,使用 lambda 函数来获取“_this”而不是“this”等,但是“移植到 TypeScript”的最佳实践是什么?