我可以更改javascript"this"的上下文吗?

Hca*_*tek 26 javascript this dom-events

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);   
};
Run Code Online (Sandbox Code Playgroud)

这可能吗?谢谢,〜在圣地亚哥

Jam*_*mes 44

不,这是不可能的.

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


Dan*_*man 9

您无法更改函数内部this引用的内容.

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


the*_*jxc 7

JP是对的.这是不可能的.请参阅JavaScript语言规范文档ECMA-262.您可以从这里下载标准:

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

该文件是ECMA-262.pdf和第39页的10.1.7节.

10.1.7这

每个活动执行上下文都有一个此值.此值取决于调用者和正在执行的代码类型,并在控制进入执行上下文时确定.与执行上下文关联的此值是不可变的.

注意"是不可变的".即无法改变.