JavaScript custom object

1, Create an object using object

<script>
        // create object
        var stu = new Object()
        // Adding properties to an object
        stu.name='jibu'
        stu[9527] = 'jibu'  //Special attribute names use square brackets
        // Adding methods to objects
        stu.study = function(){
            console.log('study')
        }
        // Calling object properties and methods
        console.log(stu.name,stu['name'])
        //Call method
        stu.study()
    </script>

2, Creating objects using constructors

 <script>
        // 1. Define a constructor to create an object
        function Student() {
            // Object properties
            this.name = 'jibu'
            this.age = 18
                //Object method
            this.study = function() {
                console.log('I am learning......')
            }
        }
        // 2. Call constructor to create object
        var stu = new Student()
        console.log(stu.name)
        stu.study()

        // Define a constructor with parameters
        // Define a constructor to create an object
        function Student(name, age) {
            // Object properties
            this.name = name
            this.age = age
                //Object method
            this.study = function() {
                console.log('I am learning......')
            }
        }
        //Call constructor to create object
        var stu = new Student('tom', 18)
        console.log(stu.name)
        stu.study()
    </script>

Three literal creation object

var stu = {
            name: 'jibu',
            age: 100,
            'Special variable':1111
            study: function() {
                console.log('I am learning')
            },
            show: function() {
                console.log('My name is' + this.name, 'Age:' + this.age)
            }
        }
        console.log(stu.name)
        console.log(stu['Special variable']
        

Four this keywords

this represents the current object

  • this in the function represents the current object calling the function
  • this in the anonymous callback function bound to the event represents the event source
  • this in the constructor represents the current object of new in the future

Example 1

<script>
        // this in the function represents the caller of the function
        var a = 1

        function f1() {
            var a = 2
            console.log(this)
                // Solve the problem of local variable and global variable with the same name
            console.log('local variable: ', a)
            console.log('global variable: ', window.a)
            console.log('global variable: ', this.a)

        }
        f1()
    </script>

Example 2

    <script>
        window.onload = function() {
            document.querySelector('#btn').onclick = function() {
                console.log(this) //Here this represents the target element of the event triggered by the event source
            }
        }
    </script>
</head>

<body>
    <button id="btn">Button</button>
</body>

Example 3

<script>
        function Student(name, age) {
            // this in the constructor represents the current object of new in the future 
            this.name = name
            this, age = age
        }
    </script>

V. basic data types and reference data types

Basic data type
string,number,boolean,undefined,null

<script>
        var a = 5
        var b = a
        b = 8
        console.log(a)
        console.log(b)
    </script>

Creating variables A and B and referring to a is equivalent to assigning a value, and modification does not affect each other

Reference data type
object,array,Student...

<script>
        var stu1 = {
            name: 'tom',
            age: 18
        }
        var stu2 = stu1; //Assign stu1 address to stu2
        stu1.name = 'alice'
        console.log(stu1.name)
        console.log(stu2.name)
    </script>

It will be found that the operation is the same as the basic data type, but the results are different, which will affect each other,
Here comes the memory problem

There are two types of memory:

  • Stack memory
    The references of variables of basic data type and variables of reference data type will be stored in stack memory, and the access speed is relatively fast
  • Heap memory
    Variables that reference data types will be stored in heap memory, and the access speed is slow

Variables referring to data types are stored in the stack (memory address), and their objects are stored in the heap. stu2 refers to stu1, which is actually the same reference to memory address. The results are the same when all modifications are made


The variables and values of basic data types are stored in the stack. Give the value of a to b, and all modifications will not affect each other

Six closure

How to understand closures?

  • A function is defined inside a function, and the function defined inside is a closure
  • Closures are functions that can read internal variables of other functions
  • A closure is a function defined in a scope that can access all variables in the scope
  • In terms of function, closure is a bridge connecting internal and external functions of a function

Use of closures

  • Inside the function, you can read the variables inside the function
  • Keep the value of the variable in memory all the time

Use of closures

    <script>
        function add() {
            for (var i = 1; i <= 5; i++) {
                var li = document.createElement('li')
                li.innerText = 'li' + i
                li.onclick = function() {
                    console.log('Click on page' + i + 'li')
                }
                document.getElementById('myul').appendChild(li)
            }
        }
    </script>
    <style>
        ul {
            width: 300px;
            height: 300px;
            border: 1px solid #ccc;
        }
    </style>
</head>

<body>
    <button onclick="add()">Add element</button>
    <ul id="myul">

    </ul>
</body>


Because the loop ends when you click the element button, and all that you always get is the last one, which forms a closure

Solution 1:
Not defined inside the function. Define the function outside and call it inside the function

<script>
        function add() {
            for (var i = 1; i <= 5; i++) {
                var li = createLi(i)
                document.getElementById('myul').appendChild(li)
            }
        }

        function createLi(num) {
            var li = document.createElement('li')
            li.innerText = 'li' + num
            li.onclick = function() {
                console.log('Click on page' + num + 'li')
            }
            return li
        }

Solution 2:
Add attributes to the element to store variables

<script>
        function add() {
            for (var i = 1; i <= 5; i++) {
                var li = document.createElement('li')
                li.innerText = 'li' + i
                li.num = i; //Store data
                li.onclick = function() {
                    console.log('Click on page' + this.num + 'li')
                }
                document.getElementById('myul').appendChild(li)
            }
        }
    </script>

Solution 3:
Using let to define variables
Block level scope. The area where the declared variable is located will not receive external influence, which is called temporary scope

<script>
        function add() {
            for (let i = 1; i <= 5; i++) {
                var li = document.createElement('li')
                li.innerText = 'li' + i
                li.onclick = function() {
                    console.log('Click on page' + i + 'li')
                }
                document.getElementById('myul').appendChild(li)
            }
        }
    </script>

7, Jason

JavaScript Object Notation is a lightweight data exchange format, which is used to represent JavaScript objects. It adopts text format independent of programming language, which is easy to write and read, and easy to parse and generate

Basic Usage
{"attribute name": "attribute value", "attribute name": "attribute value"...}

be careful

  • The Json structure is composed of a series of key value pairs, which are called Json objects
  • Attribute names use double quotes
  • The difference between JSON and object literals: JSON attributes must use double quotation marks, while object literals can be omitted

Compliance attribute

<script>
        //The composite attribute value is a json object
        var user = {
            "name": {
                "firstName": "ji",
                "lastName": "bu"
            },
            "age": 100
        }
        console.log(user.name.firstName)
    </script>

Collection of Json objects

<script>
        //The composite attribute value is a json object
        var user = [{
                    "id": 1,
                    "firstName": "ji",
                    "lastName": "bu"
                }, {
                    "id": 1,
                    "firstName": "ji",
                    "lastName": "bu"
                }, {
                    "id": 1,
                    "firstName": "ji",
                    "lastName": "bu"
                },

            ]
            //loop
        for (var i = 0; i < user.length; i++) {
            console.log(user[i])
        }
    </script>

JSON operation

 <script>
        //Convert JSon object to string
        var stu = {
            "id": 1,
            "name": "jibu"
        }
        console.log(typeof stu)
        var str = JSON.stringify(stu);
        console.log(typeof str)


        // Convert string to JSON
        var str = '{"id": 1,"name": "jibu"}'
        console.log(typeof str)

        var obj = JSON.parse(str)
        console.log(typeof obj)
    </script>

Keywords: Javascript Front-end TypeScript

Added by danieliser on Mon, 03 Jan 2022 07:59:26 +0200