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

In-depth analysis of MySQL query interception

Table of contents 1. Query Optimization 1. MySQL ...

Page Refactoring Skills - Javascript, CSS

About JS, CSS CSS: Stylesheet at the top Avoid CS...

Comprehensive understanding of HTML basic structure

Introduction to HTML HyperText Markup Language: H...

Website Design Experience Summary of Common Mistakes in Website Construction

Reminder: Whether it is planning, designing, or de...

js to implement web calculator

How to make a simple web calculator using HTML, C...

Sample code for displaying a scroll bar after the HTML page is zoomed out

Here is a record of how to make a scroll bar appe...

vue3 timestamp conversion (without using filters)

When vue2 converts timestamps, it generally uses ...

Two types of tab applications in web design

Nowadays, tabs are widely used in web design, but...

How to add Nginx proxy configuration to allow only internal IP access

location / { index index.jsp; proxy_next_upstream...

Implementation of Docker container state conversion

A docker container state transition diagram Secon...

Two ways to implement square div using CSS

Goal: Create a square whose side length is equal ...

Two box models in web pages (W3C box model, IE box model)

There are two types of web page box models: 1: Sta...

Problems installing TensorRT in docker container

Uninstall the installed version on Ubuntu: sudo a...