Function constructor and its objects and methods

1. Basics

Function is a constructor that can create a Function object, that is, every function in JavaScript is actually a Function object.

Constructor:   new Function ([arg1[, arg2[, ...argN]],] functionBody) 

Description: arg1, arg2, etc. are the parameters of the constructor, and functionBody is the method body. Note: Parameters must be surrounded by quotes!

Example:

var plus=new Function("a","b","return a+b");  
var result=plus(1,2);//调用,返回3  

The above method to create a function is equivalent to the normal function declaration method:

  function plus(a,b){return a+b;};  

Highlights:

1. The object generated by the Function constructor is parsed when the function is created (that is, the model of the object is generated when the function is actually called), so it is less efficient than the ordinary function declaration method, because the ordinary method is parsed together with other codes;

2. This method does not support closures, that is, it cannot access the private variables of the function object where it is created, but can only access variables and global variables in its own parameter list, so it is generally only used as a global function. Such as:

<script>  
 var test=1; // Global variable for testing   
var plus= new Function("a","b","return a+b+test" );  
alert(plus( 1,2)); // The result of the prompt is 4, that is, the test variable is accessed   
function adder(value){  
     var number=value; // Define a private variable   
    alert("mark 1" );  
     this .method = new Function("a","b","return a+b+number" );  
}  
var operation = new adder (1 );  
alert( "mark2" );  
alert(operation.method( 1,2)); // The mark 1 and mark 2 are prompted, but there is no result (error) here, if the number in the definition of the method is changed to the global variable test, the result 4 will be run. It can be seen that the Function constructor method does not implement closures.  
</script>  

The properties of the prototype

Attributes:

1. The arguments property: (deprecated)

function.arguments property: represents the arguments passed into the function, which is an array-like object. Obsolete. example:

function test(var1,var2){  
alert(test.arguments[0]+test.arguments[1]);  
}  

Notice:

1), use the function name to call; 2), the arguments array accesses the actual parameters passed in this function call, not the parameters of the previous call (pay attention to nested or loop calls!). It is recommended to use the arguments object inside the function: .

arguments object:

The object is a local variable inside the function, not a property of the function. Example of use:

function test(var1,var2){  
arguments[ 0]=0; // The value of the parameter can be changed   
alert(arguments[0]+arguments[1 ]);  
}  
test( 1,2); // will prompt the result to be 2  

illustrate:

The arguments object is not a real Array object, and has no array properties and methods (except length). The parameter array can be obtained by inheriting the slice method of the array: 

 
var args = Array.prototype.slice.call(arguments);  

It is not recommended to use this method to get the parameter array, because the slice method will affect the optimization of js engine (such as v8 engine). It is better to use iterating over arguments to get the arguments to generate an array.

arguments object properties:

length, callee, etc. arguments.callee returns the function constructor (that is, the function) to which the arguments object belongs, so that recursion of anonymous functions can be implemented. Such as: 

function create() {  
    return  function (n) {  
       if (n <= 1 )  
          return 1 ;  
       return n * arguments.callee(n - 1); // Call the anonymous function constructor to which the arguments belong.  
   };  
}  
var result = create()(5); // returns 120 (5 * 4 * 3 * 2 * 1)  

Description: Fully compatible.

Check out:

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Functions/arguments

2. caller attribute: return the name of the calling function

example:

function myFunc() {  
    if (myFunc.caller == null ) {  
       return ("The function is called in the global scope!"); // The caller value is null when it is called globally   
   } else   
      return ("Call me is The function is " + myFunc.caller);  
}  

Description: Fully compatible.

3. length: the number of parameters expected by the function

length is an attribute value of the function object, indicating how many parameters the function expects, that is, the number of formal parameters. Quantities do not include remaining parameters. In contrast, arguments.length is the actual number of arguments passed when the function is called.

4. name: returns the function name in string form

Example: alert(test.name);//The function name test of the test function pops up.

Note: Some browsers do not support it.

5. prototype: prototype, the most important attribute

3. Methods

apply(), call(), bind(), toSource(), toString(), isGenerator() six.

1. Apply method

Commonly used, syntax:

 B.prototype.method.apply(A [,args]); 

effect:

The method method of the prototype of the constructor B (that is, the method of the object of B, which is well understood after understanding the prototype chain) is provided to the object A, use, args is the parameter of the method that needs to be passed in, which is an array or array Literal (eg in the form [1,2]).

Notice:

B must be the constructor name (that is, the function name), and A is an object that will use this method function.

Example: 

function A(var1,var2){  
     this .v1= var1;  
     this .v2= var2;  
     // this.method=function(){ alert(this.v1+this.v2);} this method will not apply apply etc. method   
}  
A.prototype.method=function(){ alert(this.v1+this.v2);}  
function B(){  
    this.v1=10;  
    this.v2=20;  
}  
var a= new A(1,2 );  
b=new B();  
a.method(); // Prompt result: 3   
A.prototype.method.apply(b); // Apply the method method of constructor A to object b. Since method has no parameters, the parameter array is omitted.  
b.method(); // Real call, if there are parameters, you don't need to write it here, just write it in the apply parameter list. Hint result: 30  

Deeper details:

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Function/apply

2. call method

Similar to the apply method, but the parameters take the form of a parameter list.

grammar:

 fun.call(thisArg[, arg1[, arg2[, ...]]]) 
where fun is any method, using the fun method for the thisArg object also implements the simulation of inheritance (thisArg is equivalent to inheriting the fun method) .

Example:

[plain]  view plain copy  
 
function Product(name, price) {  
  this.name = name;  
  this.price = price;  
  
  if (price < 0) {  
    throw RangeError('Cannot create product ' +  
                      this.name + ' with a negative price');  
  }  
}  
function Food(name, price) {  
  Product.call( this , name, price); // Food object inherits Product method   
  this .category = 'food' ;  
}  

Food above is equivalent to:

[plain]  view plain copy  
 
function Food(name, price) {   
    this.name = name;  
    this.price = price;  
    if (price < 0) {  
        throw RangeError('Cannot create product ' +  
                this.name + ' with a negative price');  
    }  
  
    this.category = 'food';   
}  

3, bind method

grammar:

 fun.bind(thisArg[, arg1[, arg2[, ...]]]) 

effect:

Bind the fun method to the thisArg object. It is equivalent to writing the method fun in the constructor of thisArg, so the this used in fun refers to the thisArg object to which fun belongs.

Example:

[plain]  view plain copy  
 
this.x = 9;   
var module = {  
  x: 81,  
  getX: function() { return this.x; }  
};  
module.getX(); // 返回 81  
var retrieveX = module.getX;  
retrieveX(); // return 9, in this case "this" refers to the global scope  
  
// Create a new function that binds "this" to the module object   
// Newbies may be confused by the global x variable and the property x in the module   
var boundGetX = retrieveX.bind(module);  
boundGetX(); // return 81  

Function is a reference type, so it also has a length property, valueOf and toString methods. All functions should be regarded as Function objects, and the function name is a reference to the object!

The above is just the basic usage, more knowledge reference manual!

refer to:

MDN Knowledge Base Function properties and methods: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Function/caller

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325979187&siteId=291194637