JavaScript function calls are divided into 4 modes:
1. Method calling mode: that is, the object contains method attributes, Obj.methodName() or Obj[methodName]().
2. Function calling mode: methodName().
3. Constructor calling mode: new MethodName().
4. Apply and call calling modes: ObjA.apply(ObjB,args[]) or ObjA.call(ObjB,arg1,arg2...).
When a function is called, in addition to receiving formal parameters, it also receives this and arguments. Among them, this is the function object context and arguments are the actual parameters.
Apply and call implement the same function, that is, switching the context of the function object (the reference pointed to by this). The difference is that the formal parameters are different. apply is arguments or an array, call is multiple individual formal parameters separated by commas.
1 2 3 4 5 6 |
|
Before executing add.call(test,3);, both add and test belong to window, and this points to window at this time. add.call(test,3); When executing, enter the add method body. At this time, this is switched from window to test. At this time, this.a=test.a, this.b=test.b, and c are passed in as formal parameters. The value of alert() is 1 2 3=6. apply also has the same function.
Extension and inheritance through apply and call:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|