【问题标题】:Context of this in a var Foo = (function () { etc [duplicate]var Foo = (function () { etc [重复]
【发布时间】:2013-03-03 01:52:48
【问题描述】:

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

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(

【问题讨论】:

  • 函数中this的值取决于它的调用方式。
  • 请说明您对this 的使用存在问题。
  • 你最后好像少了)();

标签: javascript knockout.js typescript


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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 这本身不是一个技巧,它利用了在创建 Function 实例时发生的闭包。我已经多次使用它来为我的 ViewModel 对象提供静态 DOM 操作。
    【解决方案3】:

    我怀疑你只会有这个“类”的一个实例,从而使 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");
            }
        }
    }
    

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

    【讨论】:

    • 谢谢,但我实际上创建了这个类的一个实例:var viewModel: AlertConfigViewModel = new AlertConfigViewModel(rawJson);
    • 所以我真的不想在课堂上工作
    • 我正在使用 typescript 顺便说一句
    猜你喜欢
    • 2011-05-17
    • 2014-04-12
    • 2015-05-06
    • 2013-10-09
    • 2019-02-08
    • 2023-03-17
    • 1970-01-01
    相关资源
    最近更新 更多