Javascriptapply method example

Source: Internet
Author: User
The javascriptapply () method calls a function when specifying the this value and parameter (the parameter exists in the form of an array or a class array object. This article describes the basic syntax and examples of the apply method. For more information about the code farmers, see. apply()Method thisA function is called when values and parameters exist in the form of an array or a class array object.

Basic apply () Syntax:

fun.apply(thisArg[, argsArray])

Apply () parameter introduction:

Parameter Name Parameter description
ThisArg InfunThethis Value.Note that the specifiedthisThe value is not necessarily true when the function is executed.thisValue. If this function is in non-strict mode, it is specifiednullOrundefinedHourWill automatically pointGlobal Object (window object in the browser), and the value is the original value (number, String, Boolean value)thisWill point to the automatically wrapped object of the original value.
ArgsArray An array or a class array object. The array elements are passed as independent parameters.funFunction. If the value of this parameter isNullOrundefined. The class array object can be used from ECMAScript 5. For browser compatibility, see the content at the bottom of this article.

Usage of apply:

When calling an existing function, you can specifythisObject.thisIndicates the current object, that is, the object that is calling this function. UseapplyYou can write this method only once and inherit it from another object, instead of re-writing the method in the new object.

applyAndcall()It is very similar. The difference is that it provides parameters.applyUse a parameter array instead of a set of parameter lists (Original: a named set of parameters ).apply You can use array literal (array literal), as shown in figurefun.apply(this, ['eat', 'bananas']), Or an array object, suchfun.apply(this, new Array('eat', 'bananas')).

You can also usearguments ObjectargsArrayParameters.argumentsIs a local variable of a function. It can be used as all unspecified parameters of the called object. In this way, you do not need to know all the parameters of the called object when using the apply function. You can use arguments to pass all parameters to the called object. The called object is responsible for processing these parameters.

From ECMAScript 5th, you can use any class array object, that is, as long as there islengthAttributes and[0...length)Integer attribute of the range. For example, you can useNodeListOr a self-defined similar{'length': 2, '0': 'eat', '1': 'bananas'}Object.

Note: Chrome 14 and Internet Explorer 9 still do not accept Class array objects. If an array object is input, an exception is thrown.

Apply () instance 1:Use apply to link the constructor

You can use apply to give an object link constructor, similar to Java. In the following example, we will create a globalFunctionFunction to enable you to use a class array object in the constructor instead of a parameter list.

Function.prototype.construct = function (aArgs) {  var oNew = Object.create(this.prototype);  this.apply(oNew, aArgs);  return oNew;};

Note:TheObject.create()The method is relatively new. Another optional method is to use closures. Consider the following alternative method:

Function.prototype.construct = function(aArgs) {  var fConstructor = this, fNewConstr = function() {     fConstructor.apply(this, aArgs);   };  fNewConstr.prototype = fConstructor.prototype;  return new fNewConstr();};

Use Case:

function MyConstructor () {    for (var nProp = 0; nProp < arguments.length; nProp++) {        this["property" + nProp] = arguments[nProp];    }}var myArray = [4, "Hello world!", false];var myInstance = MyConstructor.construct(myArray);console.log(myInstance.property1);                // logs "Hello world!"console.log(myInstance instanceof MyConstructor); // logs "true"console.log(myInstance.constructor);              // logs "MyConstructor"

Note:This non-nativeFunction.constructMethod and some native Constructor (for exampleDate. In this case, you must useFunction.bindMethod (for example, imagine that the next array should be used in the Date constructor:[2012, 11, 4]In this case, you need to write:new (Function.prototype.bind.apply(Date, [null].concat([2012, 11, 4])))()--In any case, this is not the best implementation method and may not be used in any production environment ).

Apply () instance 2:Use applyAnd built-in functions

The clever apply method allows you to use built-in functions in some tasks that originally need to be written to traverse array variables. In the following example, we will use Math. max/Math. min to find the Maximum/minimum value in an array.

/* min/max number in an array */var numbers = [5, 6, 2, 3, 7];/* using Math.min/Math.max apply */var max = Math.max.apply(null, numbers); /* This about equal to Math.max(numbers[0], ...) or Math.max(5, 6, ..) */var min = Math.min.apply(null, numbers);/* vs. simple loop based algorithm */max = -Infinity, min = +Infinity;for (var i = 0; i < numbers.length; i++) {  if (numbers[i] > max)    max = numbers[i];  if (numbers[i] < min)     min = numbers[i];}

But be careful: if you use the following method to call apply, You may encounter a problem where the number of method parameters exceeds the limit.When you pass in a very large number of parameters (for example, more than parameters) to a method, it is very likely to cause cross-border problems, this critical value depends on different JavaScript Engines, because this limit (in fact, it is also a natural manifestation of any behavior that uses ultra-large stack space) is not specified. some engines throw an exception. worse, other engines directly limit the number of parameters passed into the method, resulting in parameter loss. (For example, if an engine limits the maximum number of method parameters to four [the actual number of parameters is much higher, for example], in the above Codeapply The parameters passed to the target method are 5, 6, 2, 3, rather than the complete numbers array .) if your parameter array may be very large, we recommend that you use the following policy to process it: Split the parameter array and pass it into the target method cyclically:

function minOfArray(arr) {  var min = Infinity;  var QUANTUM = 32768;  for (var i = 0, len = arr.length; i < len; i += QUANTUM) {    var submin = Math.min.apply(null, arr.slice(i, Math.min(i + QUANTUM, len)));    min = Math.min(submin, min);  }  return min;}var min = minOfArray([5, 6, 2, 3, 7]);

Apply () instance 3:Use apply in "monkey-patching"

Apply can be used as the best way to build built-in functions in the Firefox or JS library of monkey-patch. For the someobject. foo function, you can modify this function in the left-side way, as shown in the following code:

Var originalfoo = someobject. foo; someobject. foo = function () {// console before calling the function. log (arguments); // call this function as usual: originalfoo. apply (this, arguments); // do something after calling here .}

This method works with debug events or APIs, such as multiple. on ([event]... events, such as those available in Devtools Inspector ).

Note: the syntax of this function is almost identical to that of the call () method. The only difference is that the call () method accepts a list of parameters while the apply () method () the method accepts an array (or a class array object) containing multiple parameters ).

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.