Always think that you understand the meaning of this in JS, thisalways points to the object that invokes the method, as a method call, then this is the object instantiated. but a few days ago, I wrote a script and encountered a strange problem.
The code is as follows:
Internal object Autocompleteinner function Autocompleteinner (transformresultinner) {if (Transformresultinner) { This.transformresultinner=transformresultinner;} } AutoCompleteInner.prototype.transformResultInner = function () {alert ("inner Transformresult"); } AutoCompleteInner.prototype.TestInner = function () {This.transformresultinner (); }//Encapsulates call function Autocompleteouter (obj) {This for internal object Autocompleteinner. TextField = obj. TextField; This. Valuefield = obj. Valuefield; if (obj.transformresult) {this.transformresultouter = Obj.transformresultouter; }} autocompleteouter.prototype.transformresultouter=function () {alert ("TextField:" +this. Textfield+ ", Valuefield:" +this. Valuefield); }autocompleteouter.prototype.testouter = function () {var test =new Autocompleteinner (this.transformresultouter); Test. Testinner ();}
Test Code 1
Test Code 1 function test () { var obj={}; Obj. TextField = "TextField"; Obj. Valuefield = "Valuefield"; var temp=new autocompleteouter (obj); Temp.transformresultouter (); }
Pop-up reality content for "Textfield:textfield,valuefield:valuefield" This is easy to understand, In the instance Autocompleteouter method Transformresultouter This is the instance of the Autocompleteouter temp, the popup content is natural and reasonable, in line withas a method invocation, this refers to the instantiated object.
Test Code 2
function test () { var obj={}; Obj. TextField = "TextField"; Obj. Valuefield = "Valuefield"; var temp=new autocompleteouter (obj); Temp.transformresultouter (); Temp. Testouter (); }
By analyzing the code, it is found that the call is also Autocompleteouter method Transformresultouter, but: the problem is:
the pop-up content is " textfield:undefined,valuefield:undefined "
Strangely, the method of invoking the same passed parameters is also kind, but why pop-up content is not the same?
After analysis found in the code of test two the meaning and testing of this The This in the code in one is not the same, and the this in test one represents an instance of Autocompleteouter, but in Test II This represents autocompleteinner instances, This is why the same code shows why the content is different.
appears this always points to the object that invokes the method. That's the fundamental way to differentiate this. This is context-sensitive, how mechanically understood