1 when a function is saved as an attribute of an object, we call it a method. When a method is called, this is bound to the object.
2 When a function is not an object's property, then when it is invoked, this is bound to the global object. This flaw causes this of the intrinsic function to not necessarily be the this of the function that called it, and the solution is to define a new variable in the external function to point to this (for example, var that = this; )。
3 with new in front of a function, a new object is created, this is bound to the newly object.
4 apply can simulate a scene in which an object owns and executes the function, and the first parameter passes the object to This,null to represent the Global object window, and the second parameter passes the sequence of parameters required to execute the function.
The test code is as follows:
var myobject={"a": "Init a", "B": "Init B", "": "Empty"};
PT ("myobject[\" \ "]");//property name can be an empty string myobject.outerfunc=function (mystr) {var that=this;//definition that for internal function access The Var innerfunc=function (mystr) {//Internal function This does not point to MyObject put (' in Innerfunc \ ' this\ ' is '
+ (typeof this.b));
if (typeof that=== "undefined") {put ("This is undefined");
}else{//Replace this with "use" that\ "reset B");
THAT.B=MYSTR;
}
};
Innerfunc ("Reset B");
THIS.A=MYSTR;
} pt ("Myobject.a");
PT ("myobject.b");
Put ("Call outerfunc ...");
Myobject.outerfunc ("Reset a");
PT ("myobject.b");
PT ("Myobject.a");
var Quo = function (string) {this.status = string;
};
Quo.prototype.get_status = function () {return this.status;
}; var myquo = new Quo ("confused");
PT ("Myquo.get_status ()");
The var add = function (a,b) {put (this.location);//later will pass window to this return a+b;
} var myarray = [3,4];
var sum = add.apply (Null,myarray);//equivalent to Window.add (Myarray[0],myarray[1]) pt ("sum");
var statusobject = {status: "A-ok"}; var status = Quo.prototype.get_status.apply (Statusobject);//equivalent to Statusobject.get_status () pt ("status");