JavaScript call and apply

来源:互联网 发布:ipadair2淘宝清除缓存 编辑:程序博客网 时间:2024/05/16 15:47

In JavaScript:

f.call(o);f.apply(o);

is equivalent to :

o.m = f; // Make f a temporary method of o.o.m(); // Invoke it, passing no arguments.delete o.m; // Remove the temporary method.

Actually, in strict mode, the first argument of call and apply method becomes the invocation context of the function even if it is of primitive type or null or undefined, but in non-strict mode of ECMAScript 5 or in ECMAScript 3, the invocation context is replaced with the global object or the corresponding wrapper object.

Any arguments to call() after the first invocation context argument are the values that are passed to the function that is invoked:

f.call(o,args...)
The apply() method is like the call() method, except that the arguments to be passed to the function are specified as an array:

f.apply(o,[arg1,arg2...]).
Note that apply() works with array-like objects as well as true arrays.

In particular, you can invoke a function with the same arguments as the current function by passing the arguments array directly to apply().
The following code demonstrates :

// Replace the method named m of the object o with a version that logs// messages before and after invoking the original method.function trace(o, m) { var original = o[m]; // Remember original method in the closure. o[m] = function () { // Now define the new method.  console.log(new Date(), "Entering:", m); // Log message.  var result = original.apply(this, arguments); // Invoke original.  console.log(new Date(), "Exiting:", m); // Log message.  return result; // Return result. };}
This trace() function is passed an object and a method name. It replaces the specified method with a new method that “wraps” additional functionality around the original method. This kind of dynamic alteration of existing methods is sometimes called “monkey-patching.”

0 0
原创粉丝点击