The nature, definition, calling, parameters and return values of functions in JS

Programming in an object-oriented way, not in a process oriented way

 

Object is a collection of various types of data, which can be numbers, strings, arrays, functions, objects

Objects are stored as key value pairs

Object to assign to a variable

    var cat={
        "name":"Meow 1",
        "age":4,
        "family":["Meow Dad","Meow mom"],
        "speak":function(){
            console.log("Meow meow~");
        },
        "friend":{
            "name":"Meow 2",
            "age":5
        }
    }

Above is the way to create the literal quantity of the object, simple and direct

In addition, there are ways to create constructors for objects

    var cat=new Object();

There is also a new way of adding JavaScript 5

This method has compatibility problems in older browsers

    Object.create();

Get, set, add, and modify the value of an object:

Object. Property name = property value

Object [property name] = property value

    var cat={
        "name":"Meow 1",
        "age":4,
        "family":["Meow Dad","Meow mom"],
        "speak":function(){
            console.log("Meow meow~");
        },
        "friend":{
            "name":"Meow 2",
            "age":5
        }
    }

    cat.name="Meow meow 1";
    cat.age=6;
    cat.type="English short";
    console.log(cat.name);//Meow meow 1
    console.log(cat["age"]);//6
    console.log(cat.type);//English short

To delete an object's properties:

delete object. Property

    var cat={
        "name":"Meow 1",
        "age":4,
        "family":["Meow Dad","Meow mom"],
        "speak":function(){
            console.log("Meow meow~");
        },
        "friend":{
            "name":"Meow 2",
            "age":5
        }
    }

    cat.type="English short";
    console.log(cat.type);//English short

    delete cat.type;
    console.log(cat.type);//undefined

Check whether the object has a property:

Property name in object

    var cat={
        "name":"Meow 1",
        "age":4,
        "family":["Meow Dad","Meow mom"],
        "speak":function(){
            console.log("Meow meow~");
        },
        "friend":{
            "name":"Meow 2",
            "age":5
        }
    }

    console.log("name" in cat);//true
    console.log("type" in cat);//false

Enumeration of objects, traversing the properties of objects

    var cat={
        "name":"Meow 1",
        "age":4,
        "family":["Meow Dad","Meow mom"],
        "speak":function(){
            console.log("Meow meow~");
        },
        "friend":{
            "name":"Meow 2",
            "age":5
        }
    }

    for(var p in cat){
        console.log(p);
        //name age family speak friend
    }
    var cat={
        "name":"Meow 1",
        "age":4,
        "family":["Meow Dad","Meow mom"],
        "speak":function(){
            console.log("Meow meow~");
        },
        "friend":{
            "name":"Meow 2",
            "age":5
        }
    }

    for(var p in cat){
        console.log(p+": "+cat[p]);

        console.log(p);//Get property name
        //console.log(cat.p);// Wrong writing
        console.log(cat[p]);//Get attribute value correctly written

        console.log(cat["n"+"ame"]);//Meow 1  []String splicing and other operations can be added in
    }

Anonymous functions, such as:

window.onload=function(){

}

After the function is executed once, the local scope and local variables will be destroyed, so external cannot call to

But the function itself has not been destroyed, and it can be called and executed many times

 

Why use a function:

Code reuse (own code and others' code, such as jquery)

Unified modification and maintenance

Increase program readability

 

The nature of function: object

Definition method: literal definition, constructor definition

//Literal definition
function add(n1,n2){

}
//Constructor definition
new Function("n1","n2","....");

Functions, like objects, can add properties and methods

function person(){
    console.log("cyy");
}
//Add attribute
person.age=25;
//Adding method
person.speak=function(words){
    console.log(words);
}
console.log(person.age);//25
person.speak("hh~");//hh~
person();//cyy

Functions can be used as data values:

Save as data value in a variable

var fn=function(){
    return "This is a function";
}
console.log(fn());//This is a function
console.log(fn);
/*
ƒ (){
    return "This is a function ";
}
*/

At this point, fn prints out the function ontology

Functions can also be used as parameters:

function fn(){
    alert(1);
}
setTimeout(fn,1000);//Transfer function ontology is required here
//Parenthesis is not allowed here. If parenthesis is added, it will be called immediately instead of waiting for 1 second

The function can be used as a return value:

function fn(){
    return function(){
        console.log("fn Medium fn");
    }
}
//call
var newFn=fn();
newFn();//fn Medium fn

// perhaps

fn()();//fn Medium fn

Three ways to define functions

// Literal measure

    // function statement
    function add(){

    }

    // var Assignment expression
    var add=function(){

    };

//Constructor
    var add=new Function("num1","num2","return num1+num2");
    add();

Difference:

Literal method is simpler than constructor method

The most important difference is the pre parsing

The function declared by the fund can be called first and then created

Function pre parsing will be defined in advance

    add();
    function add(){
        return 1;
    }

If the function created with var assignment expression is called first and then created, an error will be reported

Because var is assigned undefined during pre parsing

    add();
    var add=function(){
        return 1;
    };

function declaration and var assignment expression declaration are both good choices

Constructor is too complex, not recommended

 

Location of function definition

Functions in global scope can be called anywhere

add();
function add(){
    add();
}
add();

function fn(){
    add();
}

Functions in local scope

    //fn();  Unable to call
    function add(){
        fn();
        function fn(){
            fn();
            function fn3(){
                fn();
            }
        }
        function fn2(){
            fn();
        }
    }
    //fn();  Unable to call

The inner layer can access the functions of the outer layer, while the outer layer cannot access the functions of the inner layer

Functions defined in the code block:

Because there is no block level scope in js, it is still in the global scope

Functions are declared in advance in pre parsing

if(true){
    function fn1(){

    }
}else{
    function fn2(){
        
    }
}

Change to the following so that the declaration can be made according to the conditions, also because of the mechanism of pre parsing

if(true){
    var fn1=function (){

    }
}else{
    var fn2=function fn2(){

    }
}

Functions in objects

Call with object. Function name

var person={
    name:"cyy",
    setAge:function(age){
        this.age=age;//this Point to current object
    }
}
person.setSex=function(sex){
    this.sex=sex;
}
person.setAge(25);
person.setSex("girl");
console.log(person.age);//25
console.log(person.sex);//girl

Calls to normal functions:

Calls to named functions

function add(){

}
add();

Calls to anonymous functions:

If you call directly after anonymous functions with parentheses, an error will be reported

function(){
    alert(1);
}();//Uncaught SyntaxError: Unexpected token (

The solution is to assign the code executed by this anonymous function to a variable

var fn=function(){
    alert(1);
}();//1

The second solution:

Enclose functions in parentheses to realize anonymous function self execution

(function(){
    alert(1);
})();//1

Parentheses around the whole can achieve the same effect

(function(){
    alert(1);
}());//1

Or add legal characters before function, such as+-~

!function(){
    alert(1);
}();//1

Or put it in console.log

console.log(function(){
    alert(1);
}());

The common purpose of the above methods is to prevent anonymous function from appearing at the beginning

 

Recursive call:

Call yourself

Factorial realization

function fn(num){
    if(num<=1) return 1;
    return num*fn(num-1);
}
console.log(fn(5));
/*
return 5*fn(4)
return 5*4*fn(3)
return 5*4*3*fn(2)
return 5*4*3*2*fn(1)
return 5*4*3*2*1
*/

Anonymous function is also a function. When it is self executing, it will create its own function internal scope, which will be destroyed after execution. Therefore, it cannot access the internal of self executing anonymous function externally

//Create function internal scope here
(function add(n1,n2){
    return n1+n2;
})();
console.log(add(3,4));//The function inside the function cannot be accessed globally add

Method call:

Method in object, calling with object. Method name

var operation={
    add:function(n1,n2){
        return n1+n2;
    },
    sub:function(n1,n2){
        return n1-n2;
    }
}
console.log(operation.add(3,4));//7

This is also the method below. When we click the browser, the browser will automatically help us to complete the call;

You can also use method calls to make calls

    document.onclick=function(){
        alert(1);
    }
    document.onclick();//Equivalent to clicking on the screen

About the properties in the object, when to quote and when not to quote

For legal identifiers, you can use them without quotation marks;

Illegal identifier, must be quoted, otherwise error will be caused

var operation={
    add:function(n1,n2){
        return n1+n2;
    },//Legal attribute names can be without quotation marks
    sub:function(n1,n2){
        return n1-n2;
    },
    "@":function(){

    }//Illegal attribute name, which will cause error, must be quoted
}

Legal identifier. The object and method name are used when calling

Illegal identifier, called with object ["method name"]

var operation={
    add:function(n1,n2){
        return n1+n2;
    },//Legal attribute names can be without quotation marks
    sub:function(n1,n2){
        return n1-n2;
    },
    "@":function(word){
        alert(word);
    }//Illegal attribute name, which will cause an error, must be quoted
}
console.log(operation.add(2,5));//7
console.log(operation["@"]("hh~"));//hh~

[] difference between quoted and unquoted

var operation={
    add:function(n1,n2){
        return n1+n2;
    },//Legal attribute names can be without quotation marks
    sub:function(n1,n2){
        return n1-n2;
    },
    "@":function(word){
        return word;
    },//Illegal attribute name, which will cause error, must be quoted
    key:function(n1,n2){
        return "key~";
    }
}
var key="add";
console.log(operation.key(2,3));//key~
console.log(operation["key"](2,3));//key~
console.log(operation[key](2,3));//5

Chain call of method

Such as jquery

$("p").html("html").css("color","red")....

To use a chained call in an object, you need to return the current object in the method

var operation={
    add:function(n1,n2){
        console.log(n1+n2);
        return this;
    },
    sub:function(n1,n2){
        console.log(n1-n2);
        return this;
    }
}
operation.add(5,3).sub(4,2);
//To ensure operation.add(5,3)Can return operation object
//You need to add return this

Call to constructor:

Constructors are generally capitalized when they are named

Call with the new + function name, the return value is an object

function Person(){

}
var obj=new Person();

The built-in constructors in js are:

Object()
new Object()

Array()
new Array()

Called through the new keyword

Define objects and arrays as constructors and add content

var person=new Object();
person.name="cyy";

var arr=new Array();
arr[0]=1;

Indirect call of function

. call: the first parameter is to change the direction of this, and the way to pass parameters is one by one

. apply: the first parameter is to change the direction of this, and the way to pass the parameter later is through array (or class array)

var name="cyy";
var person={};
person.name="cyy2";
person.getName=function(){
    return this.name;//Here this point person object
}
console.log(person.getName());//Direct call  cyy2

console.log(person.getName.call(window));//Indirect call, at this time this Directed at window,The return is window.name  cyy
console.log(person.getName.apply(window));//Indirect call  cyy
function add(n1,n2){
    return n1+n2;
}
console.log(add(1,2));//Direct call 3
console.log(add.call(window,1,2));//Indirect call 3
console.log(add.apply(window,[1,2]));//Indirect call 3
function add(n1,n2){
    return n1+n2;
}
var arr=[4,6];
console.log(add.apply(window,arr));//10

Only functions have call and apply methods. The only difference between them is their parameter passing method

 

Parameters of function

The essence of parameter passing is to assign parameters to parameters

Number of parameters

1. Number of formal parameters = number of real parameters

function add(n1,n2){
    return n1+n2;
}
console.log(add(3,5));

2. Number of real parameters < number of formal parameters

Mostly used when there are optional parameters

function pow(base,pow=2){
    return Math.pow(base, pow);
}
console.log(pow(3));//9
console.log(pow(3,3));//27

3. Number of real parameters > number of formal parameters

If you don't know how many arguments there are, you can use arguments

Arguments is an array of classes that hold information about arguments

Get a parameter through arguments[index]

arguments.length the number of arguments

function add(){
    if(arguments.length==0) return;
    var sum=0;
    for(var i=0,len=arguments.length;i<len;i++){
        sum+=arguments[i];
    }
    return sum;
}
console.log(add());//undefined
console.log(add(1,2,3,4,5));//15

arguments is an array of classes, essentially an object

The index is an array subscript. The variable name at the beginning of the number is illegal. Therefore, quotation marks are required

{
    '0': 1,
    '1': 2,
    '3': 4,
    length: 3
}

Parameters can be modified by arguments

function speak(m){
    arguments[0]="";
    return m;
}
console.log(speak("hh"));//empty

arguments are unique to each function and do not cross functions

function fn1(){
    console.log(arguments);//Arguments [1, callee: ƒ, Symbol(Symbol.iterator): ƒ]
    function fn2(){
        console.log(arguments);//Arguments [2, callee: ƒ, Symbol(Symbol.iterator): ƒ]
    }
    fn2(2);
}
fn1(1);

Arguments.call refers to the function itself

function add(){
    console.log(arguments.callee);
}
add();

Arguments.call is often used in recursion

function factorial(num){
    if(num==1) return 1;
    return num*factorial(num-1);
}
console.log(factorial(5));//120


function factorial(num){
    if(num==1) return 1;
    return num*arguments.callee(num-1);
}
console.log(factorial(5));//120

However, in strict mode, arguments.call is not allowed (and var is not allowed to declare variables)

The solution at this time is to assign a function to a variable, so that the name of the function itself does not affect the call

"use strict";

var myfn=function factorial(num){
    if(num==1) return 1;
    return num*factorial(num-1);
}
console.log(myfn(5));//120

arguments.length

The number function name of the parameter. Length or arguments.call.length

function add(n1,n2){
    if(arguments.length != add.length) throw new Error("Please introduce"+add.length+"A parameter!");
}
console.log(add(5));//Uncaught Error: Please pass in 2 parameters!

What are the parameters

1. No parameters

2. Number as parameter

3. String (if DOM node is selected, $("p"))

4. Boolean value (keep the purity of function, suggest a function to do only one thing)

5. undefined (optional parameters must be placed last)

6,null

7, array

$.each(["a","b","c"],function(index,item)){
    console.log(index);//0 1 2
    console.log(item);//a b c
}

8, object

$.each({name:"cyy",age:24},function(index,item)){
    console.log(index);//name age
    console.log(item);//cyy 24
}

Benefits of using objects as parameters (free to swap order)

function fn(obj){
    var person={};
    person.name=obj.name||"cyy";
    person.age=obj.age||24;
    person.tel=obj.tel||110,
    person.addr=obj.addr||"China";
    return person;
}
var cyy={
    name: "cyy1",
    age:25
}
console.log(fn(cyy));//{name: "cyy1", age: 25, tel: 110, addr: "China"}

9, function

Callback functions, such as setTimeout(fn, time);

 

Return value of function

return:

End of function

Return value

What can be returned:

Direct return. The return value is undefined

number

String: the output of alert() is all strings. The. toString() method will be called by default

Boolean: commonly used for form validation

null and undefined

array

function add(n1,n2){
    return [n1,n2,n1+n2];
}
console.log(add(5,6));//(3) [5, 6, 11]

object

function fn(){
    return {
        name:"cyy",
        age:25
    }
}

Note that do not wrap the line after return, otherwise the default is semicolon, and this is the end. Then the following will report an error

function fn(){
    //return By default, it's followed by a semicolon. It's over
    return 
    {
        name:"cyy",
        age:25
    }
}

function

It needs to be called with () ()

 

When document.write() is executed, the. toString() method is called to try to convert the result to string form

document.write([1,2,3]);//1,2,3
document.write({
    name:"cyy"
});//[object Object]
document.write({
    name:"cyy",
    toString:function(){
        return "hh~";
    }
});//hh~
function count(){
    var num=1;
    return function(){
        return num++;
    }
}
//Each call count()At that time, num Will be initialized
//also return num++ First return num,Re execution++
console.log(count()());//1
console.log(count()());//1
console.log(count()());//1
//count()Only once, so num Initialize only once
//It can be incremented every time+1
var fn=count();
console.log(fn());//1
console.log(fn());//2
console.log(fn());//3

Tags: Javascript Attribute JQuery Programming

Posted on Wed, 12 Feb 2020 08:07:33 -0500 by sasquatch69