In javascript development, we often get the event objects on the page and process these events. For example, the getEvent function below gets the page event objects under javascript.
Copy to ClipboardReference: [www.bkjia.com] function getEvent (event ){
Return event | window. event;
}
We can call this method when using getEvent.
Copy to ClipboardReference: [www.bkjia.com] function foo (event ){
Var evt = getEvent (event );
Alert (evt );
}
And bind the foo function to an onclick event.
However, the commonly used foo function does not have parameters, or the first parameter is not passed in. We can obtain the first parameter through arguments [0.
In IE, event is a global variable, that is, window. event. In Firefox and other browsers, the event is passed into the foo function as the first parameter, so the getEvent can be changed:
Copy to ClipboardReference: [www.bkjia.com] function getEvent (event ){
Return arguments [0] | window. event;
}
In this case, Some browsers, such as Firefox, may fail to obtain the event object. In fact, we can see that the event triggering method is as follows:
Copy to ClipboardReference: [www.bkjia.com] function onclick (event ){
Foo ();
}
In this way, the first function is onclick, that is, the event will be passed in as the first parameter by default, while the foo function does not pass in the event as the parameter, which seriously limits the flexibility of getEvent, therefore, we need to modify the getEvent function.
We know that arguments. callee is the function itself and can be used as recursion in anonymous functions. arguments. callee. caller refers to the function that calls the upper-level function of this function.
For example, the caller of getEvent is foo, the caller of foo is onclick, and so on ......
Therefore, our getEvent function can be written as follows:
Copy to ClipboardReference: [www.bkjia.com] function getEvent (){
If (window. event ){
Return window. event;
}
Var f = arguments. callee. caller;
Do {
Var e = f. arguments [0];
If (e & (e. constructor === Event | e. constructor === MouseEvent | e. constructor === KeyboardEvent )){
Return e;
}
} While (f = f. caller );
}