What are the rules for context in JavaScript functions?

What are the rules for context in JavaScript functions?

1. Rule 1: Object.Method()

對象.方法()
When an object is dotted and its method function is called, the context of the function is the dotted object.

1.1 Case 1

function fn() {
    console.log(this.a + this.b);
}
var obj = {
    a: 66,
    b: 33,
    fn: fn
}
obj.fn();

Output:

99

1.2 Case 2

var obj1 = {
    a: 66,
    b: 33,
    fn: function () {
        console.log(this.a + this.b);
    }
}
var obj2 = {
    a: 66,
    b: 33,
    fn: obj1.fn
}
obj2.fn();

Output:

7

1.3 Case 3

function outer() {
    var a = 11;
    var b = 22;
    return {
        a: 33,
        b: 44,
        fn: function () {
            console.log(this.a + this.b);
        }
    }
}
outer.fn();

Output:

77

1.4 Case 4

function fun() {
    console.log(this.a + this.b);
}
var obj = {
    a: 1, b: 2, c: [{ a: 3, b: 4, c: fun }]
};
var a = 5;
obj.c[0].c();

Output:

7

2. Rule 2: Function()

函數()
Parentheses call the function directly, and the context of the function is the window object.

2.1 Case 1

var obj1 = {
    a: 1, b: 2, fn: function () {
        console.log(this.a + this.b);
    }
}
var a = 3;
var b = 4;
var fn = obj1.fn;
fn();

Output:

7

2.2 Case 2

function fun() {
    return this.a + this.b;
}
var a = 1;
var b = 2;
var obj = {
    a: 3, 
    b: fun(), // Apply rule 2
     fun: fun
}
var result = obj.fun(); // Rule 1 applies
console.log(result);

Output:

6

3. Rule 3: Array subscript

數組下標
An array (array-like object) enumerates functions for invocation, and the context is this array (array-like object).

3.1 Case 1

var arr = ['A', 'B', 'C', function () {
    console.log(this[0]);
}];
arr[3]();

Output:

A

3.2 Case 2

function fun() {
    arguments[3]();
}
fun('A', 'B', 'C', function () {
    console.log(this[1]);
});

Output:

B

4. Rule 4: IIFE

(function(){})();
The context of a function in an IIFE (Immediately Executable Function) is the window object.

4.1 Case 1

var a = 1;
var obj = {
    a: 2,
    fun: (function () {
        var a = this.a; // Rule 1 applies
        return function () { // Rule 4 applies
            console.log(a + this.a); // 2+1
        }
    })()
};
obj.fun();

Output:

3

5. Rule 5: Timers and Delays

setInterval(函數,時間);
setTimeout(函數,時間);
The timer and delay call function uses the window object as the context.

5.1 Case 1

var obj = {
    a: 1, b: 2, fun: function () {
        console.log(this.a + this.b);
    }
}
var a = 3;
var b = 4;
setTimeout(obj.fun, 2000); // Rule 5 applies

Output:

7

5.2 Case 2

var obj = {
    a: 1, b: 2, fun: function () {
        console.log(this.a + this.b);
    }
}
var a = 3;
var b = 4;
setTimeout(function () {
	obj.fun(); //Apply rule 1
}, 2000);

Output:

3

6. Rule 6: Event Handling Function

DOM元素.onclick = function(){};
The context of an event handler is the DOM element to which the event was attached.

6.1 Case 1

Please achieve the effect: whichever box is clicked will turn red, and the same event handling function must be used to achieve this.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Rule 6: Event Handling Function</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        body div {
            float: left;
            width: 100px;
            height: 100px;
            margin-right: 10px;
            border: 1px solid #000;
        }
    </style>
</head>

<body>
    <div id="box1">1</div>
    <div id="box2">2</div>
    <div id="box3">3</div>
    <script>
        function changeColor() {
            this.style.backgroundColor = 'red';
        }
        var box1 = document.getElementById('box1');
        var box2 = document.getElementById('box2');
        var box3 = document.getElementById('box3');
        box1.onclick = changeColor;
        box2.onclick = changeColor;
        box3.onclick = changeColor;
    </script>
</body>

</html>

Result:

insert image description here

6.2 Case 2

Please achieve the effect: click on a box and the box will turn red after 2000 milliseconds. The same event handling function is required to achieve this.

Difference from case 1: A backup context is required.

function changeColor() {
    var self = this; // backup context setTimeout(function () {
        self.style.backgroundColor = 'red';
    }, 2000);
}
var box1 = document.getElementById('box1');
var box2 = document.getElementById('box2');
var box3 = document.getElementById('box3');
box1.onclick = changeColor;
box2.onclick = changeColor;
box3.onclick = changeColor;

This is the end of this article about the context rules in JavaScript functions. For more information about JavaScript function context rules, please search previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • JavaScript function syntax explained
  • JavaScript functional programming basics
  • JavaScript Basics Series: Functions and Methods
  • Detailed explanation of the differences between var, let and const in JavaScript es6

<<:  Detailed explanation of how to use Tomcat Native to improve Tomcat IO efficiency

>>:  HTML Tutorial: HTML horizontal line segment

Recommend

Causes and solutions for MySQL master-slave synchronization delay

For historical reasons, MySQL replication is base...

The difference between MySQL count(1), count(*), and count(field)

Table of contents 1. First look at COUNT 2. The d...

CentOS 8 officially released based on Red Hat Enterprise Linux 8

The CentOS Project, a 100% compatible rebuild of ...

Solution to prevent caching in pages

Solution: Add the following code in <head>: ...

Linux series of commonly used operation and maintenance commands (summary)

Table of contents 1. System monitoring 2. File Op...

Nginx request limit configuration method

Nginx is a powerful, high-performance web and rev...

HTML input box optimization to improve user experience and ease of use

In order to improve user experience and ease of us...

5 ways to migrate Docker containers to other servers

Migration is unavoidable in many cases. Hardware ...

Detailed usage of js array forEach instance

1. forEach() is similar to map(). It also applies...

Input file custom button beautification (demo)

I have written such an article before, but I used...

Solve the problem that ifconfig and addr cannot see the IP address in Linux

1. Install the Linux system on the virtual machin...

Detailed explanation of DOM style setting in four react components

1. Inline styles To add inline styles to the virt...

How to use CSS attribute selectors to splice HTML DNA

CSS attribute selectors are amazing. They can hel...

Implementation of crawler Scrapy image created by dockerfile based on alpine

1. Download the alpine image [root@DockerBrian ~]...