【问题标题】:Can I change the context of javascript "this"?我可以更改javascript“this”的上下文吗?
【发布时间】:2010-11-06 06:41:57
【问题描述】:
var UI$Contract$ddlForm_change = function() {

    //'this' is currently the drop down that fires the event
    // My question is can I change the context so "this" represents another object? 
    this = SomeObject;

    // then call methods on the new "this"
    this.someMethod(someParam);   
};

这可能吗?

【问题讨论】:

标签: javascript this dom-events


【解决方案1】:

不,这不可能。

您可以为 this 调用具有指定值的方法(使用 method.apply()/method.call())但不能重新分配关键字,this

【讨论】:

  • 更多信息joshuakehn.com
  • 您也可以在调用UI$Contract$ddlForm_change时将this作为参数传递给函数,然后您可以将该参数用作上下文/访问其属性
【解决方案2】:

您无法从函数内部更改this 所指的内容。

但是,您可以调用特定上下文中的函数 - 以便 this 引用特定对象 - 通过使用 callapply

【讨论】:

    【解决方案3】:

    J-P 是正确的。这不可能。请参阅 JavaScript 语言规范文档 ECMA-262。您可以从这里下载标准:

    http://www.ecma-international.org/publications/standards/Ecma-262.htm

    该文件是 ECMA-262.pdf,在第 39 页,第 10.1.7 节。

    10.1.7 这个

    有一个关联的 this 值 每个活动的执行上下文。这 这个值取决于调用者和 正在执行的代码类型,并且是 当控制进入 执行上下文。这个值 与执行上下文相关联 是不可变的。

    注意“是不可变的”。即无法更改。

    【讨论】:

      猜你喜欢
      • 2011-04-14
      • 2021-10-19
      • 2011-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多