Home > Web Front-end > JS Tutorial > body text

How to use JavaScript functions? Introduction to the properties and methods of JavaScript functions

不言
Release: 2018-08-03 17:19:30
Original
1629 people have browsed it

What is JavaScript function? Functions in JavaScript are actually objects, because each function is an instance of the Function constructor and has the properties and methods defined by the Function constructor. Let's take a closer look at the properties and methods of JavaScript functions.

The function name is actually a pointer to the function object. See the following code:

    function sum(a,b) {
        return a + b;
    }
    // 相当于把sum的引用地址传递给sum2。
    // 注意:不带圆括号的函数名是访问函数指针,而非调用函数
    var sum2 = sum; 
    sum2(1,2) // 3
    sum = null;
    sum(2,3) // undefined // 将sum的内存回收,即sum的引用地址变了
    sum2(2,3) //5 // 但sum2 还是指向原来的内存地址
Copy after login

The above code can illustrate the problem that the function name is actually a pointer to the function object. After understanding the above problems, we can conduct the following analysis:

1. No overloading

After understanding the above, reload Loading is equivalent to re-modifying the reference value of the function variable, so the previous one will be overwritten later, which is easy to understand.

2. Function promotion

#In fact, it is similar to variable promotion. It is the difference between declarative functions and expression-defined functions. It is very simple

3. Function as value

Because the function name itself is a variable, it can be passed as a value. Here is a good example, It is also a good programming idea, as follows:

function getSomeFunction(fn,arg) {
    return fn(arg);
} 
function add(num) {
    return num + 10;
}
function getGreeting(name) {
    return `Hello ${name}`;
}
getSomeFunction(add,5) // 15
getSomeFunction(getGreeting,'andy') // Hello andy
Copy after login

You can also return another function from one function. For example, when we use some sorting methods or iteration methods of arrays, because what is passed in is a function variable as a parameter, we can write this parameter using the "external function return function" method. The advantage of this is, The returned function can pass in the parameters we "specifically want to specify" for calculation. For example, the parameter of the

// 规定利用哪个属性进行排序,如果不填则代表数组从大到小排序
function sortArgFuntion(compareProperty) { //compareProperty是上文中特定想要规定的参数

    return function (val1, val2) {
        if (compareProperty === undefined) {  // 如果排序的是数组的值,则用常规的方法
            if (val1 > val2) {
                return 1;
            } else if (val1 < val2) {
                return -1;
            } else {
                return 0;
            }
        } else {    // 如果排序的是对象的属性则用该方法
            if (val1[compareProperty] > val2[compareProperty]) {
                return 1;
            } else if (val1[compareProperty] < val2[compareProperty]) {
                return -1;
            } else {
                return 0;
            }
        }

    }
}
var data = [{
    name: 'andy',
    age: 25
}, {
    name: 'Nf',
    age: 29
}]
data.sort(sortArgFuntion('name'))
Copy after login

sort function is a function used to reorder the array. And when we take out the function parameters, we can write this function more intuitively and with higher reusability to achieve the effect we want. At the same time, you need to carefully study and understand the essence and uniqueness of the function return function

4. Internal properties of the function

There are two special properties inside the function Variables

  • arguments

  • this

arguments

is an array-like object. What is an array-like object? Array-style access can be performed through serial numbers (such as obj[1]), and there is a length attribute (if you do not define the length attribute of the object, it does not have length). The class array only has the index value and length, and does not have various methods of the array, so If you want to call an array method like an array, you need to use Array.prototype.method.call to implement

this

this is very JavaScript A confusing and complex point of knowledge, what it represents depends entirely on the calling location, I will but list a summary this. e.g:

window.color = 'red';
var o = {color:"blue"};
function sayColor() {
    console.log(this.color)
}
sayColor(); // red 因为调用位置是全局
o.sayColor = sayColor;
o.sayColor(); // blue 因为调用位置是o的对象里
Copy after login

We need to know from the above example that the function name is just a pointer. Although the execution environment is different, the global sayColor() and the o.sayColor() in the function point to the same function.

caller

Newly added in es5, it returns the calling environment of the current function (must be a function, not an object). If the calling environment is global, null is returned. There are two usages, one is the function name plus caller, the other is arguments.callee.caller

    function outer() {
        console.log(outer.caller); //null
        inner();
    };
    function inner() {
        console.log(inner.caller); // outer里的代码
    }
Copy after login

5. Function attributes and methods

Because functions are also objects, they also have properties and methods; there are two properties in the function: length and prototype. Length refers to the number of parameters passed in.
function add(num1,num2) {} console. log(add.length) // 2

propertype

For reference types, propertype is the real place where all instance methods are saved. When creating custom reference types and implementing inheritance, its role and key (how many key points are not yet understood, especially the word inheritance:)) In es5, property type is not enumerable, so it cannot be traversed .

apply() and call()

Two parameters, the first parameter is the scope in which to run, and the second parameter apply is the incoming Array Or the arguments object, call passes in each value, and the rest are exactly the same. This is one of the examples to illustrate the role of apply and call:

    var color = "red";
    var o = {color:"blue"};
    function sayColor() {
        alert(this.color)
    }
    sayColor(); // red
    sayColor.call(this); // red 
    sayColor.call(window); // red
    sayColor.call(o); // blue
Copy after login

If we don’t use call, we need to do this:

    var color = "red";
    var o = {color:"blue"};
    function sayColor() {
        alert(this.color)
    }
    o.sayColor = sayColor;
    o.sayColor(); //blue
Copy after login

So the comparison can be seen at a glance. The biggest role of call is to achieve Decoupling objects and methods

bind method

The bind method is used to construct an instance of a function, and its this object points to the scope specified by bind.

For example:

    var color = "red";
    var obj = {color:"blue"}
    function sayColor() {
        console.log(this.color);
    }
    var bindSayColor = sayColor.bind(obj);
    bindSayColor(); // blue
Copy after login

Recommended related articles:

javascript function

Javascript ordinary functions and constructs The difference between functions

Detailed explanation of function declaration and call in JavaScript

The above is the detailed content of How to use JavaScript functions? Introduction to the properties and methods of JavaScript functions. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template