One, this point problem
1) method invocation as an object
When a function is called as a method of an object, this points to the object, such as Obj.geta (); This points to the previous function caller; Accordingly, the This inside the event handler function is also the node that points to the occurrence of the event;
2) as a normal function call
In the normal function, this points to the Global object window;
3) Constructor Call
When a function is called with the new operator, the function returns an object, and this in the constructor points to the returned object, and it is important to note that if the constructor explicitly returns an object of the type object, the result of this operation will eventually return the object. This also points to this object in the constructor, not the this that we expect;
Second, this loss problem
Consider the following question, in a framework such as prototype.js, to do something like this:
var getid=function (ID) { return document.getElementById (ID); } var odiv=getid ('div1');
Think about why not use the following simpler way:
var getid=document.getElementById; var odiv=getid ('div1');
The latter throws an exception, because this is used internally by many engine document.getElementById methods, and this is expected to point to document when getElementById is invoked as a method. This point has no problem, but when GetID is used to refer to Documant.lgetelementbyid, it becomes the call of the ordinary function, which in its function points to the window rather than the desired doucment;
You can try this fix using the following method:
Document.getelementbyid=(Function (func) { return function () { func.apply (document, arguments); } ) (document.getElementById); var getid=document.getElementById; var div=getid ('div1');
Iii. Call and apply
1. These two functions can specify the point of this, apply using an array or an array of classes as parameters, call the number of parameters is not fixed, in this sense, apply is more than the frequency of use, if the first parameter passed in is null, it is called as a normal function, This points to window at this point;
2. The purpose of these two functions in some cases is not to point to this, but to borrow other objects, such as class arrays such as arguments add data can be borrowed [].prototype.push.call; conversion to a real array can take []. Prototype.slice.call; intercept elements can be borrowed [].prototype.shift.call; the key to borrowing is that the internal implementation principles of these functions also apply to objects of class arrays, as long as the following conditions are met:
1) The object itself can be accessed by the digital subscript property;
2) The Length property of the object can read and write;
The idea that the $ object in the jquery framework is designed into an array of classes is probably the result.
The second--this of JavaScript design pattern learning