1, the use of this
1) As the object's method call, this refers to the object itself
var obj={A:1, geta:function() { alert (this ===obj); Output: True // output: 1 } }
Obj.geta ();
2) as a normal function call, this refers to the Window object
Window.name= ' Globalname '; var myobject={ name:' Seven ', getName:function() { Returnthis. Name;} ; var getname=// output Globalname
Here is the variable GetName reference Myobject.getname method. If it is myobject.getname(), it will output seven, which is a property call belonging to the object.
3) constructor call, this refers to the object returned by the constructor
var myclass=function() { this. Name= ' seven ';}; var obj=New MyClass (); alert (obj.name);
If the object object is returned explicitly, it is eventually returned instead of this
var myclass=function() { this. Name= ' seven '; return { name:' Anne ' } }; var obj=New MyClass (); alert (obj.name);//output Anne
If the returned non-object type, such as a string, will still output seven.
4) Function.prototype.call or Function.prototype.apply call
is used to specify the pointer to the this object within the function.
The difference between call and apply:
A) The first parameter of apply specifies the point of the This object, and the second parameter is an indexed collection, which can be an array or an array of classes.
var func=function(a,b,c) { alert ([A,b,c]); output [};func.applay](null//null points to the default host object, window in the browser.
b) One of the parameters of call is the same as apply to specify the This object, followed by multiple parameters.
var func=function(a,b,c) { alert ([A,b,c]); // output [I/O] };func.call (null//null points to the default host object, which is window in the browser. )
Resolve the missing issue with the normal function call this
Window.name= ' Globalname '; var myobject={ name:' Seven ', getName: (function() { return This . Name; }) }; var getname=myobject.getname; // output Seven
JavaScript Design Patterns and open practice Learning (a) JavaScript implementation polymorphism 2