This pointer always points to an object that can be roughly divided into the following four types:
1, method invocation as an object (this points to the object)
2, as a normal function call
When a function is not called as an object's property, that is, the normal function, at which point this always points to the global object. In the browser's JavaScript, the global object is Windows.
1 window.name= ' globainame '; 2 var getname=function () {3 return this.name;4};5 console.log (GetName ());
This points to the global object
3, constructor call
There are no classes in JavaScript, but you can create objects from the constructor and also provide the new operator, which makes the constructor look more like a class.
When a function is called with the new operator, the function always returns an object, usually the this in the constructor points to the returned object
var MyClass () { this.name= ' Sven ';}; var obj=new MyClass (); alert (obj.name);
This in the constructor
However, if the constructor shows an object of type objects returned, the result will eventually return the object.
var MyClass () { this. name= ' Sven '; return { // Display Returns an object name: ' Anne ';}}; var obj=New MyClass (); alert (obj.name); // output Anne
constructor Display returns object Type
4,function.prototype.call and Function.prototype.apply
Their role is the same, the difference is in the form of incoming parameters. Apply accepts two parameters, the first parameter specifies the pointer to the this object in the function body, and the second parameter acts as an indexed collection, either as an array or as an array of classes.
The number of arguments passed in the call is not fixed, the first parameter specifies the pointer to the this object in the function body, starting with the second argument, each of which is passed to the function sequentially.
If the first argument we pass in is null, the this in the body of the function points to the default host object, which is window in the browser.
1document.getElementById = (function(func) {2 return function(){3 returnfunc.apply (document,arguments);4 }5 }) (document.getElementById);6 varGetId =document.getElementById;7 vardiv = getId (' Div1 ');8alert (div.id);//Output Div1
use apply to fix this point
This call and apply