function object (apply, call, bind)
This article refers to the detailed arrangement of MDN, easy to refer to [MDN] (Https://developer.mozilla.org/zh-CN/docs/Web/JavaScript)
The function constructor creates a new function object. In JavaScript, each function is a functional object.
Constructors
new Function ([arg1[, arg2[, ... ArgN],] functionbody)
- Arg1, arg2, ... argN The name of the argument used by the function must be a valid JavaScript identifier string
- Functionbody A string containing a JavaScript statement that includes a function definition.
- The constructor that calls function (not with the new keyword) in the same way as the constructor is called.
Example:var adder = new Function("A", "B", "return a + B" c20>); Created a function that can return two parameters
Adder(2, 6);//8
Function objects that are generated by using the function constructor are resolved when the functions are created. This is more inefficient than using function declarations or function expressions (functions) and calling them in your code, because the functions created with the latter are parsed with other code .
All arguments passed to the constructor are treated as arguments to the function being created, and are the same identifier name and order of delivery.
Functions generated using the function constructor do not create closures in the context in which they are created; they are typically created in the global scope. When these functions are run, they can only access their own local variables and global variables, and cannot access the scope of the generated context called by the function constructor. This is not the same as using eval with function-expression code.
Property:
Function.length
Length is a property value of a function object that indicates how many parameters the function expects, that is, the number of formal parameters. The number does not include the remaining parameters . In contrast, arguments.length is the number of actual arguments that are invoked when the function is called.
- The function constructor itself is also a function. The value of his length property is 1. The property writable: false, Enumerable: false, configurable: true.
- The value of the length property of the Function prototype object is 0.
Method
Function.prototype.call (thisarg[, arg1[, arg2[, ...])
A method that applies another object in the context of an object thisarg; A parameter can be passed in as a list, that is, a function or method is called with a specified this value (thisarg) and a number of specified parameter values.
- It should be noted that the specified This value is not necessarily the actual this value when the function executes , and if the function is in non-strict mode , it is specified as null and the This value of undefined automatically points to the global object (which is the Window object in the browser), and this value is the original value (number, String, Boolean), which points to the automatic wrapper object for that original value.
application of the call method:
- invoking a function using the call method and specifying the ' this ' of the context
function greet () { var reply = [This] role].join ('); Console.log (reply);} var a =' Douglas crockford ', role: ' Javascript Developer '// Douglas Crockford is an Awesome Javascript Developer
- Use the call method to invoke the parent constructor: in a child constructor, you can implement inheritance by calling the call method of the parent constructor
function Food (name, price) {product.call (This, name, price); this. Category = ' food ';}
- Use the call method to invoke the anonymous closure function to achieve the purpose of binding this and passing parameters
for (var i =0;i<10;i++) {setTimeout(function() {console.log (i); }.call (null, i), 0)}// can output 0~9 smoothly, if not call, then the final value of I, output 10
Function.prototype.apply (thisarg[, Argsarray])
A method that applies another object in the context of one object, and the parameter can be passed in as an array.
- Thisarg The This value that is specified when the function is run . It is important to note that the specified this value is not necessarily the true this value when the function executes , or NULL if the function is in a non-strict mode. Undefined automatically points to the global object (which is the Window object in the browser), and this value is the original value (number, String, Boolean), which points to the automatic wrapper object for that original value.
- Argsarray an array or class array object (ES5 new,Chrome 14 and Internet Explorer 9 still do not accept class array objects.) If you pass in a class array object, they throw an exception. ), where the array elements are passed as separate arguments to the function. If the value of this parameter is null or undefined, it means that no parameters need to be passed in. Class array objects can be used starting from ECMAScript 5. For browser compatibility, see the bottom of this article.
- With apply and call, you can write this method once and then inherit it from another object without repeating the method in the new object.
- You can use the arguments object as the argsarray parameter. arguments is a local variable of a function. It can be used as all unspecified parameters of the called object. This way, you do not need to know all the parameters of the called object when you use the Apply function. You can use arguments to pass all parameters to the called object.
Using apply and built-in functions
The smart apply usage allows you to use built-in functions in certain tasks that you would otherwise have to write to iterate over the array variables. In the next example we will use Math.max/math.min to find the maximum/minimum value in an array.
var numbers = [5, 6, 2, 3, 7];var max = Math.max.apply (null, numbers); var min = Math.min.apply (null, numbers);
- When you pass a very many parameters (such as more than 1W) to a method, it is very likely to cause cross-border problems, which are based on different JavaScript engines (JavaScript cores have been limited to the number of hard-coded parameters 65536 because this restriction (which is actually the natural manifestation of any behavior that uses super-large stack space) is unspecified. Some engines throw exceptions. What's worse is that the other engine directly restricts the number of arguments passed into the method, causing the parameter to be lost.
- If your parameter array is likely to be very large, it is recommended to use the following strategy: to dice the array of parameters into the target method:
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]);
Function.prototype.bind (thisarg[, arg1[, arg2[, ...])
The bind () method creates a new function (the new function has the same function body as the called function) and is called a binding function.
- When this binding function is called, the binding function passes the first parameter of the bind () method as this when it is created, passing in the Second and later arguments of the bind () method as the default parameters of the binding function. The parameters of the binding function itself are called in order as arguments to the original function.
- A binding function can also use the new operator to create an object: This behavior is like using the original function as a constructor. The supplied this value is ignored, while the parameter at the time of invocation is supplied to the impersonation function.
bind usage:
The simplest use of bind () is to create a binding function for the original function that binds to the specified object so that the function has the same this value regardless of how it is called
this.x = 9;var module = {x:81, getx:function () {return this.x;}}; Module.getx (); Returns 81var Retrievex = Module.getx;retrievex (); Returns 9, in this case, "this" points to all scopes//creates a new function that binds "this" to the Module object///The Novice may be confused by the Global x variable and the attribute x in module = var boundgetx = Retrievex.bind (module); Boundgetx (); Returns 81
Another simplest use of bind () is to make a function have a preset initial parameter
Function List () {return Array.prototype.slice.call (arguments);} var list1 = list (1, 2, 3); [1, 2, 3]var leadingthirtysevenlist = list.bind (undefined, notoginseng); var list2 = Leadingthirtysevenlist (); [37]var list3 = Leadingthirtysevenlist (1, 2, 3); [37, 1, 2, 3]
function foo (x, y) {return y? X+y:foo.bind (void 0,x)}console.log (foo (1,4)); 3console.log (foo (1) (4)); 3
With SetTimeout, when window.settimeout () is used by default, the This keyword points to a window (or Global) object. When you use a method of a class that requires an instance of this reference class, you may need to explicitly bind this to the callback function in order to continue using the instance.
functionLatebloomer () { This. Petalcount = Math.ceil (Math.random () * 12) + 1;} LateBloomer.prototype.bloom=function() {window.settimeout ( This. Declare.bind ( This), 1000);}; LateBloomer.prototype.declare=function() {Console.log (' I am a beautiful flower with ' + This. Petalcount + ' petals! ');};varFlower =NewLatebloomer (); Flower.bloom ();//after one second, call \ ' declare\ ' method
Function.prototype.toString ()
Gets the string that implements the source code for the function. Overrides the Object.prototype.toString method.
Native Js:function object (apply, call, bind) detailed