Summary of JavaScript function usage and precautions

Time:2020-1-26

This article describes the use and precautions of JavaScript function (function type). To share with you for your reference, as follows:

In ECMAScript, the function type is actually an object. Each function is an instance of the function type and has the same properties and methods as other reference types. Because a function is an object, the function name is actually a pointer to the function object.

Key learning points:

1. How to declare a function
2. Function as value
3. Internal properties of functions
4. Function properties and methods

1、 How to declare a function

1. Common function declaration


function box(num1, num2) {
  return num1+ num2;
}

2. Initialize functions with variables


var box= function(num1, num2) {
  return num1 + num2;
};

3. Use function constructor


var box= new Function('num1', 'num2' ,'return num1 + num2');

PS: the third way is not recommended, because this syntax will result in code parsing twice (the first time regular ECMAScript code is parsed, and the second time string in the incoming constructor is parsed), thus affecting performance. But we can understand the concept of “function is an object, function name is a pointer” through this syntax.

2、 Function as value

The function name in ECMAScript itself is a variable, so the function can also be used as a value. That is, you can not only pass a function to another function as you pass parameters, but also return a function as the result of another function.

function box(sumFunction, num) {
  return sumFunction(num); //someFunction
}
function sum(num) {
  return num + 10;
}
Var result = box (sum, 10); // transfer the function to another function

3、 Function internal properties

Inside the function, there are two special objects:argumentsandthisargumentsIs an array like object, which contains all the parameters in the passed in function. Its main purpose is to save the function parameters. But this object has another namecalleeIs a pointer to theargumentsObject.

function box(num) {
  if (num <= 1) {
    return 1;
  } else {
    Return num * box (num-1); // a simple recursion
  }
}

For factorial function, recursive algorithm is generally used, so the function will call itself; if the function name does not change, there is no problem, but once the function name is changed, the internal call needs to be modified one by one. To solve this problem, we can usearguments.calleeInstead.

function box(num) {
  if (num <= 1) {
    return 1;
  } else {
    Return num * arguments.call (num-1); // use call to execute itself
  }
}

Another special object inside the function isthis, whose behavior is similar to this in Java and C ා. let me put it another way,thisIt refers to the object on which the function performs the operation, or the scope of the function call statement. PS: when a function is called in the global scope,thisObject refers to window.

//Easy to understand rewriting examples
Window. Color = 'Red'; // global, or var color = 'Red'; OK
Alert (this. Color); // print the global color
var box = {
  Color: 'Blue', // local color
  sayColor : function () {
    Alert (this. Color); // this can only be the color in the box at this time
  }
};
Box. Saycolor(); // print local color
Alert (this. Color); // Global
//Original examples of cited textbooks
Window. Color = 'Red'; // or var color = 'Red'; OK

var box = {
  Color: 'Blue'
};
function sayColor() {
  Alert (this. Color); // it's outside for the first time and inside the box for the second time
}
getColor();
Box. Saycolor = saycolor; // copy the function to the box object as the method
box.sayColor();

4、 Function properties and methods

Functions in ECMAScript are objects, so functions also have properties and methods. Each function has two properties:lengthandprototype。 Where the length property indicates the number of named parameters the function expects to receive.


function box(name, age) {
  alert(name + age);
}
alert(box.length); //2

PS: forprototypeProperty, which is the real place to save all instance methods, that is, the prototype. This property is described in detail in the object-oriented chapter. andprototypeThere are two ways:apply()andcall(), each function contains these two non inherited methods. The purpose of these two methods is to call functions in a specific scope, which is actually equivalent to setting the value of the this object in the function.

function box(num1, num2) {
  Return num1 + num2; // original function
}
function sayBox(num1, num2) {
  Return box. Apply (this, [num1, num2]; // this is the scope, here is window
}// [] indicates the required parameters of box
function sayBox2(num1, num2) {
  Return box.apply (this, arguments); // arguments object represents the parameters required by box
}

alert(sayBox(10,10)); //20
alert(sayBox2(10,10)); //20

call()Method inapply()Methods are the same, but they differ only in the way they receive parameters. aboutcall()Method, the first parameter is scope, there is no change, only the rest of the parameters are directly passed to the function.

function box(num1, num2) {
  return num1 + num2;
}
function callBox(num1, num2) {
  Return box. Call (this, num1, num2); // the difference between this and apply lies in the following parameters
}
alert(callBox(10,10));

In fact, passing parameters is notapply()andcall()Methods are really useful; what they often use is the ability to extend the scope on which a function operates.

Var color = red '; // or window. Color = red'; OK
var box = {
  Color: 'Blue'
};
function sayColor() {
  alert(this.color);
}
Saycolor(); // scope in window
Saycolor. Call (this); // the scope is in window
Saycolor. Call (window); // the scope is in window
Saycolor. Call (box); // the scope is in box, and the object pretends to be

This example is modified from the previous scope understanding example. We can find that when we usecall(box)Method,sayColor()The running environment of the method has become the box object.

Usecall()perhapsapply()The biggest benefit of extending the scope is that the object does not need to have any coupling relationship with the method (coupling, which means that the extension and maintenance will have a chain reaction). That is, box objects andsayColor()There will be no redundant associated operations between methods, such asbox.sayColor = sayColor;

For more information about JavaScript, please refer to our special topics: summary of common JavaScript function skills, introduction to JavaScript object-oriented course, summary of JavaScript error and debugging skills, summary of JavaScript data structure and algorithm skills, and summary of JavaScript mathematical operation usage

I hope this article will be helpful for you to design JavaScript programs.

Recommended Today

PHP realizes UnionPay business H5 payment

UnionPay business H5 payment interface document: document address 1: H5 payment interface address: 1: Alipay payment Test address: http://58.247.0.18:29015/v1/netpay/trade/h5-pay Official address: https://api-mop.chinaums.com/ 2: UnionPay payment Test address: http://58.247.0.18:29015/v1/netpay/uac/order Official address: https://api-mop.chinaums.com/ 2: Basic parameters required by the interface The interface uses get parameters. After the interface parameters are directly put into the interface address, the […]