如果我在课堂上宣布这个
class AlertConfigViewModel {
DeleteAlert = function (item) {
if (item) {
if (confirm('Are you sure you wish to delete this item?')) {
this.Alerts.remove(item);
}
}
else {
alert("something is wrong");
}
};
}
它最终会像这样:
var AlertConfigViewModel = (function () {
function AlertConfigViewModel(json) {
this.DeleteAlert = function (item) {
if(item) {
if(confirm('Are you sure you wish to delete this item?')) {
this.Alerts.remove(item);
}
} else {
alert("something is wrong");
}
};
}
}
如果我在AlertConfigViewModel的上下文之外调用AlertConfigViewModel,那么“this”不是AlertConfigViewModel,我认为它会内部函数AlertConfigViewModel(
答案 0 :(得分:1)
为什么不以正常方式将您的函数声明为您的类的属性?
class AlertTest {
private alerts:string = "these-alerts";
TraceAlert():void{
console.log(this.alerts); // Logs "these-alerts", wherever it's called from
};
}
class CallTest {
private alerts:string = "not-these-alerts";
constructor() {
var target = new AlertTest (); // Creates an instance of your class, as you say.
target.TraceAlert()
}
}
var t:CallTest = new CallTest();
// Output: "these-alerts"
我不确定FuncName = function()
语法给你什么,除了范围问题。
答案 1 :(得分:1)
请查看此处发布的解决方案:TypeScript and Knockout binding to 'this' issue - lambda function needed?
如果在构造函数中定义方法体,“this”将始终指向类实例 - 这是一个技巧,但它是非常干净的解决方案。
答案 2 :(得分:0)
我怀疑你只有一个这个'类'的实例,使得这个关键字的使用过时了。
使用类似的语法尝试类似:
ClassName = {
Alerts: someObject,
DeleteAlert: function (item) {
if (item) {
if (confirm('Are you sure you wish to delete this item?')) {
ClassName.Alerts.remove(item);
}
} else {
alert("something is wrong");
}
}
}
如果你想要实例,我会选择另一种语法......