Summary of JavaScript custom object methods

Summary of JavaScript custom object methods

1. Use object to create an object

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

2. Use the constructor to create an object

<script>
        // 1. Define a constructor to create an object function Student() {
            // Object property this.name = 'jibu'
            this.age = 18
                //Object method this.study = function() {
                console.log('Learning...')
            }
        }
        // 2. Call the constructor to create an 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 property this.name = name
            this.age = age
                //Object method this.study = function() {
                console.log('Learning...')
            }
        }
        //Call the constructor to create the object var stu = new Student('tom', 18)
        console.log(stu.name)
        stu.study()
    </script>

Three literal objects

var stu = {
            name: 'jibu',
            age: 100,
            'Special variables': 1111
            study: function() {
                console.log('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 a function refers to the current object that calls the function.
  • this in the anonymous callback function of the event binding indicates the event source
  • This in the constructor represents the current object that will be new created in the future

Example 1

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

        function f1() {
            var a = 2
            console.log(this)
                // Solve the problem of local variables and global variables having the same name console.log('local variable: ', a)
            console.log('Global variables: ', window.a)
            console.log('Global variables: ', 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 source triggering the event}
        }
    </script>
</head>

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

Example 3

<script>
        function Student(name, age) {
            // this in the constructor represents the current object that will be newly created in the future this.name = name
            this.age = age
        }
    </script>

Five basic data types and reference data types

Basic Data Types

string,number,boolean,undefined,null

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

Creating a variable a and b referencing a is equivalent to assigning a copy, and modifications do not affect each other

Reference Data Types

object,array,Student…

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

Here you will find that the operations are the same as the basic data types, but the results are different and will affect each other.
This involves the memory problem

There are two types of memory:

Stack memory:

Variables of basic data types and references to variables of reference data types are stored in stack memory, and the access speed is relatively fast.

Heap memory:

Variables of reference data types are stored in heap memory, and access speed is slow

Variables of reference data types are stored in the stack (memory address), and their objects are stored in the heap. Stu2 referencing Stu1 is actually the same memory address reference, and the results are the same when all modifications are made.

Variables and values ​​of basic data types are stored in the stack. The value of a is given to b, and all modifications do not affect each other.

Six closures

How to understand closure?

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

Uses of closures

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

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('Clicked' + 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 the element button is clicked, all that is obtained is the last one, which forms a closure

Solution 1:

Do not define it 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('Clicked' + num + 'li')
            }
            return li
        }

Solution 2:

Add attributes to elements 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('Clicked' + this.num + 'li')
                }
                document.getElementById('myul').appendChild(li)
            }
        }
    </script>

Solution 3:

Defining variables using let

Block-level scope, the area where the variables are declared will not be affected by external factors, which is called temporary death

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

Seven Json

JavaScript Object Notation is a lightweight data exchange format used to represent JavaScript objects. It uses a text format that is independent of the programming language and is easy to write and read, as well as easy to parse and generate.

Basic Usage

{“屬性名”:“屬性值”,“屬性名”:“屬性值”…}

Notice:

  • The Json structure consists of a series of key-value pairs, called Json object
  • Use double quotes for attribute names
  • The difference between Json and object literals: JSON attributes must use double quotes, while object literals can be without double quotes.

Comply with attributes

<script>
        //Compound 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>
        //Compound 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 Operations

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


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

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



This is the end of this article about JavaScript custom objects. For more relevant JavaScript custom objects, please search for 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:
  • Understanding Objects in JavaScript
  • Detailed explanation of Object in Javascript
  • Detailed summary of JavaScript objects
  • Five ways to determine whether an object attribute exists in JS
  • JavaScript removes unnecessary properties of an object
  • When the springboot post interface accepts json, when it is converted to an object, the properties are all null.
  • 5 commonly used objects in JavaScript
  • Implementation of converting complex JSON string into Java nested object
  • Grasp the javascript object addition, deletion, modification and query application and examples

<<:  A brief analysis of the basic concepts of HTML web pages

>>:  Docker installation of RocketMQ and solutions to problems encountered during installation

Recommend

JS Decorator Pattern and TypeScript Decorators

Table of contents Introduction to the Decorator P...

td width problem when td cells are merged

In the following example, when the width of the td...

MySQL Database Basics: A Summary of Basic Commands

Table of contents 1. Use help information 2. Crea...

MySQL 8.0.17 installation and usage tutorial diagram

Written in front In the past and in the current p...

Three examples of blur background effects using CSS3

Let’s not start with the introduction and get str...

FastDFS and Nginx integration to achieve code analysis

FastDFS & Nginx Integration: The tracker is c...

How to change the website accessed by http to https in nginx

Table of contents 1. Background 2. Prerequisites ...

Three ways to achieve text flashing effect in CSS3 Example code

1. Change the transparency to achieve the gradual...

Usage and description of HTML tag tbody

The tbody element should be used in conjunction wi...

The implementation of Youda's new petite-vue

Table of contents Preface Introduction Live Easy ...

Common repair methods for MySQL master-slave replication disconnection

Table of contents 01 Problem Description 02 Solut...

VUE implements token login verification

This article example shares the specific code of ...

An example of vertical centering of sub-elements in div using Flex layout

1. Flex is the abbreviation of Flexible Box, whic...