JS's function call will be free two additional parameters are this and arguments. Arguments is a parameter group, he is not a real array, but you can use the. Length method to get the length.
The book says 4 call mode:
- Method invocation Pattern
- Function call pattern
- constructor invocation Pattern
- Apply Call pattern
Let's take a look at some examples to understand better.
1: Method invocation mode.
Note This now points to MyObject.
/* Method Invocation Mode */
var myobject={
value:0,
Inc:function () {
Alert (This.value)
}
}
Myobject.inc ()
2: Function call pattern
Note this at this point, point to Window
/* Function call mode */
var add=function (A, b) {
Alert (this)//this is tied to window
return a+b;
}
var sum=add (3,4);
Alert (SUM)
3: Constructor Invocation mode
The JavaScript language pristine book suggests abandoning this approach. Because there's a better way. This is not the first introduction. Post it the next time you post it.
Will add a connection here.
/* Constructor Call mode Discard */
var quo=function (String) {
this.status=string;
}
Quo.prototype.get_status=function () {
return this.status;
}
var qq=new Quo ("AAA");
Alert (Qq.get_status ());
4:apply Call pattern
= = We can look at a more useful instance of apply. Look at the bottom of the code.
/*apply*/
Note that the SUM function above is used
and MyObject
The advantage of calling in this way is that you can point to the object that this is pointing to.
The first argument to apply is the object to which this pointer is pointing
var arr=[10,20];
var sum=add.apply (Myobject,arr);
alert (sum);
See this apply real application. Bind this is a time-bound function
var bind=function (OBJECT,TYPE,FN) {
if (object.attachevent) {//ie browser
Object.attachevent ("On" +type, (function () {
return function (event) {
window.event.cancelbubble=true;//Stop Time Bubbling
Object.attachevent=[fn.apply (object)];//----Here's what I'm going to talk about here.
Add a time binding in IE with attachevent.
This is not pointing to the object itself, so. The this.id in the function we bind is not working properly.
But if we use Fn.apply (object)
Here we can see that we have changed the point of the first object of apply, which is this, to object, so this.id becomes
The object.id can work properly.
}
}) (object), false);
}else if (object.addeventlistener) {//other browsers
Object.addeventlistener (Type,function (event) {
Event.stoppropagation ();//Stop Time bubbling
Fn.apply (This)
});
}
}
Bind (document.getElementById ("AAA"), "click", Function () {alert (this.id)});
Tags: javascript
Four ways to invoke JS function