1

如果我在课堂上声明这个

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(

4

3 回答 3

1

请查看此处发布的解决方案:TypeScript and Knockout binding to 'this' issue - 需要 lambda 函数?

如果您在构造函数中定义方法主体,“this”将始终指向类实例 - 这是一个技巧,但 imo 是它非常干净的解决方案。

于 2013-03-15T11:27:11.790 回答
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()除了范围问题之外,我不确定语法给你什么。

于 2013-03-14T18:07:12.093 回答
0

我怀疑你只会有这个“类”的一个实例,从而使 this 关键字的使用过时了。

使用类似的语法尝试类似:

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");
        }
    }
}

如果你想要实例,我会选择另一种语法......

于 2013-03-14T16:17:47.473 回答