Can I change the context of javascript “this”?

百般思念 提交于 2019-11-27 15:37:40

问题


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

is this possible?


回答1:


No, it's not possible.

You can call a method with a specified value for this (using method.apply()/method.call()) but you cannot re-assign the keyword, this.




回答2:


You can't change what this refers to from inside the function.

However, you can call a function in a specific context - so that this refers to a specific object - by using call or apply.




回答3:


J-P is correct. This is not possible. Refer to the JavaScript language specification document ECMA-262. You can download the standard from here:

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

The file is ECMA-262.pdf and on page 39, section 10.1.7.

10.1.7 This

There is a this value associated with every active execution context. The this value depends on the caller and the type of code being executed and is determined when control enters the execution context. The this value associated with an execution context is immutable.

Note "is immutable". i.e. cannot be changed.



来源:https://stackoverflow.com/questions/1051237/can-i-change-the-context-of-javascript-this

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!