32
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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Hcabnettek
  • 12,678
  • 38
  • 124
  • 190
  • See the answer to this question: http://stackoverflow.com/questions/456967/javascript-how-to-set-this-variable-easily – molf Jun 26 '09 at 20:54
  • 2
    yepp, more or less a duplicate of http://stackoverflow.com/questions/456967/javascript-how-to-set-this-variable-easily The accepted answer was to use call()/apply(), see https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Function/apply – VolkerK Jun 26 '09 at 20:56
  • This is just TOO confusing. All of the answers say no, you can't do it. Apparently, the answers to the duplicate question way yes, you can do it. Go figure. – DOK Jun 26 '09 at 21:27

3 Answers3

51

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.

RobG
  • 142,382
  • 31
  • 172
  • 209
James
  • 109,676
  • 31
  • 162
  • 175
  • more informations at [joshuakehn.com](http://joshuakehn.com/2011/10/20/Understanding-JavaScript-Context.html) – vdubus Dec 11 '13 at 09:17
  • You can also pass `this` as an argument to the function in the call to `UI$Contract$ddlForm_change`, then you can use that argument as the context/access its properties – Damilola Olowookere Jan 26 '18 at 10:47
11

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.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
7

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.

the.jxc
  • 3,373
  • 21
  • 21