在var Foo = (function(){等中的上下文

Context of this in a var Foo = (function () { etc

本文关键字:上下文 function var Foo      更新时间:2023-09-26

如果我在一个类中声明这个

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(

)

为什么不以正常的方式将函数声明为类的属性呢?

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()语法给了你什么,除了范围问题。

请看这里发布的解决方案:TypeScript和Knockout绑定到'this'问题-需要lambda函数吗?

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

如果你想要实例,我会使用另一种语法