New and return in JS function

First understand the return value of the function:

When a function is called, it starts execution from the first statement inside the function and ends when it encounters the closing function body. Then the function returns control to the program that called the function.

The return statement can make the function return early. When the return statement is executed, the function returns immediately and no longer executes the remaining statements

A function always returns a value, and the return value of the function can beAny data type. If the return value is not specified by return, undefined is returned.

If the new prefix is ​​added to the front of the function call, andThe return value of the function is not a value of a reference data type, it returns the object implicitly created by the new operator

Talk about the role of the new operator:

1. Implicitly create a new empty object connected to the prototype member of the function

2. Assign the this of the function to the empty object

3. Add properties and methods to the empty object

4. Return the empty object.
If the function is created to be used in conjunction with the new operator, then the function is a constructor, and the constructor should capitalize the first letter according to the convention

In other words:

When there is a return statement inside a function and the new prefix is ​​added when calling, there are two cases:

1. What is returned after return isBasic data typeThe value of the function returns a new object created by the new operator

2. What is returned after return isReference data typeThe value of the function returns the content after the return statement

Example:

function Object(){
    
    
            return 1+1
        }
        const obj1 = new Object();
        console.log(obj1);

Insert picture description here

 function Object(){
    
    
            this.name = 'Gary',
            this.age = 23,
            this.say = function () {
    
    
                console.log(this.name)
            }
            return '123'
        }
        const obj1 = new Object();
        console.log(obj1);

Insert picture description here

function Object(){
    
    
            this.name = 'Gary',
            this.age = 23,
            this.say = function () {
    
    
                console.log(this.name)
            }
            return [1,2,3]
        }
        const obj1 = new Object();
        console.log(obj1);  

Insert picture description here

Guess you like

Origin blog.csdn.net/YL971129/article/details/113907277