Detailed explanation of function classification and examples of this pointing in Javascript

Detailed explanation of function classification and examples of this pointing in Javascript

Three ways to define functions in JS

Let me explain it with an example.

<script>
        //method1
        function fn() {
            console.log('fn created ');
        }
        //method2
        var fn2 = function () {
            console.log('fn2 created');
        }
        //method3
        var fn3 = new Function('test', 'console.log(test);');
        fn3('fn3 test');
        console.dir(fn3);
        console.log(fn3 instanceof Object);
    </script>

Running the above example proves that functions are also objects. You can use new + constructor to create an instance. The third method has low execution efficiency.

Function prototype chain

From the results, we can see that the __proto__ of the Function prototype object points to Object.

Classification and calling methods of functions in JS

Let me explain it with an example.

<script>
        //Function classification and calling method //Method 1 Ordinary standard function, this points to window
        function fn() {
            console.log('fn1' + this);
        }
        fn(); //Essentially window.fn(); Global functions are members of window //Method 2 Object method this points to the caller o
        var o = {
            sayHi: function () {
                console.log('fn2'+this);
            }
        }
        o.sayHi();

        //Mode 3 The constructor this points to the newly created object, here it points to star1
        function Star(username){
            this.username = username;
        }
        var star1 = new Star('ldh');

        //Method 4: Bind event function this to the function caller btn
        var fn = function (){
            console.log('btn was clicked' + this);
        }
        btn.onclick = fn;
        //Click the button to call the function //Method 5 Timer function The timer is actually a member of window, so this is window
        setInterval(function(){},1000);
        //The timer is called at the set time interval //Method 6: Execute the function immediately. this is window. Same as method 1 (function(){console.log('function executed')})();
//No need to call execute immediately</script>

Through the above examples, the author basically summarizes the usage of functions that he understands. By comparing method 4 and method 6,

  • We can know that adding () after the function indicates an immediate call. Without (), it indicates a function pointer, which just indicates that the function does not call the function.
  • this points to the problem, remember that this points to the caller

Change the three functions that this points to

This pointing is a very important issue in JS. In the above function classification, we have already made a systematic analysis. The following focuses on the three functions that change the this pointer.

call

Change the parent class instance to a subclass instance to implement attribute inheritance

<script>
        //call function 
        function Father(username, age) {
            this.username = username;
            this.age = age;
        }

        function Son(username, age, gender) {
            Father.call(this, username, age); //Inherit the properties of the parent class this.gender = gender;
        }
    </script>

apply

The difference between apply and call is that the parameter is an array (pseudo array). Inside apply, the array is split into elements

Mainly use the Math object, Math.max.apply(Math, [4324, 45, 342, 23])

<script>
        //apply function 
        var o = {
            username: 'testuser'
        };
        function fn(arr) {
            console.log(arr);
            for (let i = 0; i < arr.length; i++) {
                console.log(arr[i]);

            }
            console.log(this);
        }

        fn.apply(o, [23, 43]);
        console.log(Math.max(43, 45, 243, 342));
        console.log(Math.max.apply(Math, [4324, 45, 342, 23])); 
    </script>

bind

Only change the reference of this without calling the function

Use to change the this of the bound event, case

<body>
    <button>click me</button>
    <button>click me</button>
    <button>click me</button>
    <script>
        //bind function
        //Case: Implement multiple buttons to send verification codes and then send them again 3 seconds later var btns = document.querySelectorAll('button');
        for (let i = 0; i < btns.length; i++) {
            btns[i].onclick = function () {
                this.disabled = true;
                setTimeout(function () {
                    this.disabled = false; //Change this to point to btn, execute after 3000ms}.bind(this), 3000);
            }
        }        
    </script>
</body>

Summarize

This is the end of this article about function classification and this pointing in Javascript. For more relevant JS function classification and this pointing content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Detailed explanation of this pointing in JS arrow function
  • Detailed explanation of this pointing problem in JavaScript function
  • Detailed analysis of the this pointing problem inside JS anonymous function
  • In-depth understanding of the scope of js functions and this pointing
  • JavaScript makes this in the function parameter in setInteval point to a specific object
  • Detailed explanation of JavaScript function this pointing problem

<<:  A bug fix for Tomcat's automatic shutdown

>>:  Tutorial on disabling and enabling triggers in MySQL [Recommended]

Recommend

Detailed explanation of the usage and differences of MySQL views and indexes

MySQL Views Simply put, a MySQL view is a shortcu...

React Class component life cycle and execution order

1. Two ways to define react components 1. Functio...

How to enable remote access permissions in MYSQL

1. Log in to MySQL database mysql -u root -p View...

Detailed explanation of XML syntax

1. Documentation Rules 1. Case sensitive. 2. The a...

An example of how to implement an adaptive square using CSS

The traditional method is to write a square in a ...

MySQL uses the truncate command to quickly clear all tables in a database

1. Execute the select statement first to generate...

How to turn off eslint detection in vue (multiple methods)

Table of contents 1. Problem Description 2. Probl...

How to recover files accidentally deleted by rm in Linux environment

Table of contents Preface Is there any hope after...

Specific use of MySQL internal temporary tables

Table of contents UNION Table initialization Exec...

Detailed explanation of basic interaction of javascript

Table of contents 1. How to obtain elements Get i...

Sample code for seamless scrolling with flex layout

This article mainly introduces the sample code of...

The difference between MySQL execute, executeUpdate and executeQuery

The differences among execute, executeUpdate, and...

MySQL sequence AUTO_INCREMENT detailed explanation and example code

MySQL sequence AUTO_INCREMENT detailed explanatio...