This article describes how to apply and call functions in JavaScript. This article describes how to call JavaScript Functions in four modes and how to extend and inherit functions through apply and call, for more information about JavaScript function calls, see the following:
1. method call mode: the object contains method attributes, Obj. methodName () or Obj [methodName] ().
2. function call mode: methodName ().
3. constructor call mode: new MethodName ().
4. apply and call modes: ObjA. apply (ObjB, args []) or ObjA. call (ObjB, arg1, arg2 ...).
In addition to receiving format parameters, this and arguments are also received during function calls. Here, this is the context of the function object, and arguments is the actual parameter.
Apply and call implement the same function, that is, to switch the context of the function object (reference pointing to this). The difference is that the formal parameters are different. Apply is an arguments or array, and call is separated by commas.
function add(c) { alert(this.a+this.b+c); } var test={a:1,b:2} add.call(test,3);
Execute add. call (test, 3); before add and test belong to the window, this points to the window. Add. call (test, 3); During execution, 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, c is the value passed in as a parameter, that is, the result of alert () is 1 + 2 + 3 = 6. The same is true for apply.
Use apply and call to implement extension and inheritance:
Function Animal (name) {this. name = name; this. showName = function () {alert (this. name) ;}} function Cat (name) {Animal. call (this, name);} var cat = new Cat ("Black Cat"); // during execution, this of the Cat function body is switched from window to Cat {}, // this. name is passed in as a form parameter, and the final result of Cat // is cat = cat {name: "Black Cat", showName: function () {alert (this. name) ;}, cat. showName (); // during execution, this is switched from window to // Cat {name: "Black Cat", showName: functio N () {alert (this. name);} at this time, this. name // is this. name = Cat. name, so it is Black Cat.