Article From:
  • You can think of call () and apply () as an object and indirectly call functions by calling the method.
  • call()The first argument of apply () is to call the parent object of the function. It is the calling context and is referenced by this in the function body.

Using object o to call f (), you can use Call () and apply ().;

Equate to

o.m = f;    // A temporary method of storing F as oO.M (); / / / call it, no incoming parametersDelete O.M; / / remove the temporary method

Add a log before and after the call method

// Replace the method named m () in object o into another method./ / log information can be recorded before and after the original method is invoked.Function trace (O, m) {Var original = o[m];/ / save the original method in the closureO[m] = function () {/ / define new methodConsole.log (New Date (), "EnterinG: ", m); / / output log informationVar result = original.apply (this, arguments); / / calling the original functionCOnsole.log ("result:" + result);Console.log (New Date (), "Exiting:", m);Return resUlt;}}Function clazz () { = "clazz";This.sayHi = function () {RetUrn "Hi, clazz";}}Var clazz1 = new clazz ();Trace (clazz1, "sayHi");Clazz1.sayHi ();

The output results are as follows:

Sat Jun 23 2018 19:46:46 GMT+0800 (Chinese standard time) "Entering:" "sayHi"Result: Hi, clazzSat Jun 232018 19:46:46 GMT+0800 (China standard time) "Exiting:""SayHi" "
  • call The function of apply is exactly the same as that of the two party, but the way of accepting parameters is not the same.

Syntax: apply (thisObj, array parameters)
Definition: a method of applying an object, replacing the current object with another object.
Note: if a parameter is not an array type, it will report a TypeError error.

Syntax: Call ([thisObj[, arg1[, arg2[, [.ArgN]]]]]]
Definition: a method of invoking an object, replacing the current object with another object.
Explanation: the call method can be used to call another method instead of another object. The call method can change the object context of a function from the initial context to the new object specified by thisObj.
If no thisObj parameter is provided, the Global object is used as thisObj., 1, 2);
f.apply(o, [1, 2]);


  • 《JavaScriptThe sixth edition of the authoritative guide
  • JSApply, call, bind in deep understanding
Link of this Article: Apply () and call () in JavaScript

Leave a Reply

Your email address will not be published. Required fields are marked *