Front end learning notes: JavaScript classes and objects

Keywords: Javascript Front-end ECMAScript html css

Black horse Pink's advanced javaScript object-oriented ES6 tutorial:
https://www.bilibili.com/video/BV1Kt411w7MP?p=1

Based on the original tutorial, this paper sorts and cuts the directory structure. This paper summarizes the explanations, cases, PPT and source materials in the video, which are only used for personal review, learning, communication and sharing.

1. Object oriented programming

1.1 two programming ideas

  • Process oriented
  • object-oriented

1.2 POP(Process oriented programming)

Process oriented is to analyze the steps needed to solve the problem, and then use functions to realize these steps step by step. When using, you can call them one by one.

Put the elephant in the refrigerator:

  1. Open the refrigerator door
  2. Put the elephant in
  3. Close the refrigerator door

Process oriented is to solve problems according to the steps we have analyzed.

1.3 object oriented programming (OOP)

Object oriented is to decompose transactions into objects, and then divide and cooperate among objects.

Put the elephant in the refrigerator:

  1. Elephant object

    • go in
  2. Refrigerator object

    • open
    • close
  3. Use the functions of elephants and refrigerators

Object oriented is to divide problems by object functions, not steps.

Object oriented properties:

  • Encapsulation
  • Encapsulation
  • Polymorphism

2. Classes and objects in ES6

Object oriented is closer to our real life. We can use object-oriented to describe things in the real world. But things are divided into concrete things and abstract things.

Object oriented thinking characteristics:

  1. Extract (Abstract) the attributes and behaviors shared by objects, organize (encapsulate) them into a class (template)
  2. Instantiate the class and get the object of the class

In object-oriented programming, we consider which objects are there. According to the characteristics of object-oriented thinking, we constantly create objects, use objects, and command objects to do things.

2.1 object

In real life: everything is an object, an object is a concrete thing, a tangible object. For example, a book, a car and a person can be "objects", and a database, a web page and a connection to a remote server can also be "objects".

In JavaScript, an object is an unordered collection of related attributes and methods. All things are objects, such as strings, values, arrays, functions, etc.

Objects are composed of properties and methods:

  • Attribute: the characteristic of a thing, which is represented by an attribute in an object (a common noun)
  • Method: the behavior of things is expressed by method in the object (commonly used verb)

class 2.2

The concept of class is newly added in ES6. You can use the class keyword to declare a class, and then instantiate the object with this class.

Class abstracts the common part of an object. It generally refers to a large class

Object refers specifically to a class, which instantiates a specific object through a class.

2.3 creating classes

// grammar
class name {
    // class body
}
// Create instance
var xx = new name();

Note: class must use new to instantiate the object

2.4 constructor in class

The constructor() method is the constructor of the class (the default method), which is used to pass parameters and return the instance object at the same time. This method is called automatically when an object instance is generated through the new command. If there is no explicit definition, a constructor() will be automatically created inside the class.

// grammar
class Person {
  constructor(name, age) {   // Constructor construct method or constructor
      this.name = name;
      this.age = age;
    }
}    
// Create instance 
var ldh = new Person('Lau Andy', 18); 
var zxy = new Person('Xue You Zhang', 20); 
console.log(ldh);
console.log(zxy);

2.5 class addition method

// grammar
class Person {
  constructor(name,age) {   // Constructor constructor or constructor
      this.name = name;
      this.age = age;
    }
   say() {
      console.log(this.name + 'Hello');
   }
} 
// Create instance
var ldh = new Person('Lau Andy', 18); 
ldh.say();

Note: methods cannot be separated by commas, and there is no need to add function keyword.

3. Class inheritance

3.1 succession

Inheritance: subclasses can inherit some properties and methods of the parent class.

//grammar
class Father{
    // Parent class
}
class Son extends Father {
    // The subclass inherits the parent class
}

example:

class Father {
      constructor(surname) {
        this.surname= surname;
      }
      say() {
        console.log('What's your last name' + this.surname);
       }
}
class Son extends Father{  // In this way, the subclass inherits the properties and methods of the parent class
}
var damao= new Son('Liu');
damao.say();      

3.2 super keyword

super keyword is used to access and call functions on the parent class of an object. You can call the constructor of the parent class or the normal function of the parent class.

Case: calling the constructor of the parent class

class Person {   // Parent class
     constructor(surname){
         this.surname = surname;
     }
} 
class  Student extends Person { // The subclass inherits the parent class
     constructor(surname, firstname) {
         super(surname); // Call the constructor(surname) of the parent class
         this.firstname = firstname; // Define properties unique to subclasses
     }
}

Note: the subclass uses super in the constructor and must be placed before this (the constructor of the parent class must be called first, and the constructor of the subclass must be used)

Case:

class Father {
    constructor(surname) {
        this.surname = surname;
    }
    saySurname() {
        console.log('My last name is' + this.surname);
    }
}
class Son extends Father { // In this way, the subclass inherits the properties and methods of the parent class
    constructor(surname, fristname) {
        super(surname);   // Call the constructor(surname) of the parent class
        this.fristname = fristname;
    }
    sayFristname() {
        console.log("My name is:" + this.fristname);
    }
}
var damao = new Son('Liu', "Dehua");
damao.saySurname();
damao.sayFristname();  

Case: call the normal function of the parent class

class Father {
     say() {
         return 'I'm daddy';
     }
}
class Son extends Father { // In this way, the subclass inherits the properties and methods of the parent class
     say() {
          // Super. Say() super calls the method of the parent class
          return super.say() + 'My son';
     }
}
var damao = new Son();
console.log(damao.say()); 

be careful:

  1. Classes in ES6 do not have variable promotion, so you must define classes before you can instantiate objects through classes
  2. The common properties and methods in the class must be used with this
  3. The problem of this pointing in the class: this in the constructor points to the instance object, and this in the method points to the caller of this method

4. Object oriented cases

4.1 introduction

Functional requirements:

  1. Click the tab bar to switch the effect.
  2. Click the + sign to add tab items and content items.
  3. Click the x sign to delete the current tab item and content item.
  4. Double click tab item text or content item text to modify the text content.

Extract objects: tab objects

The object has the following functions:

  • switch
  • add to
  • delete
  • modify

4.2 adding functions

  1. Click + to add new tabs and content
  2. Step 1: create a new tab li and a new content section
  3. Step 2: append the two created elements to the corresponding parent element.
  4. Previous practice: create the element createElement dynamically, but there are many contents in the element. innerHTML assignment is required and appended to the parent element in appendChild.
  5. Now advanced approach: using insertAdjacentHTML(), you can directly add string format elements to the parent element
  6. appendChild does not support appending child elements of strings. insertAdjacentHTML supports appending elements of strings
  7. Insertadjacenthtml (where to append, 'string element to append')
  8. The additional position is: before end after inserting the last child node inside the element
  9. Address of the method: https://developer.mozilla.org/zh-CN/docs/Web/API/Element/insertAdjacentHTML

4.3 delete function

  1. Click × You can delete the current li tab and the current section
  2. × There is no index number, but its father li has an index number. This index number is exactly what we want
  3. So the core idea is: click the x sign to delete the li and section corresponding to the index number
  4. However, when we dynamically delete new li and index numbers, we also need to retrieve the x element and call the init method

4.4 editing function

  1. Double click the text in the tab li or section to realize the modification function
  2. The double-click event is: ondbllick
  3. If you double-click the text, the text will be selected by default. At this time, you need to double-click to prohibit the selection of the text
  4. window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty();
  5. Core idea: when you double-click the text, a text box is generated inside. When you lose focus or press enter, and then give the value entered in the text box to the original element.

4.5 complete code of demo

Link: https://pan.baidu.com/s/1FQ_6jzkpFOlsEGxuwxkcpQ Extraction code: ivht

(JavaScript advanced \ JavaScript advanced day 1 \ code - object oriented case)

Object oriented tab bar.html

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

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Object oriented tab column</title>
    <link rel="stylesheet" href="./styles/style.css">
    <link rel="stylesheet" href="./styles/tab.css">
</head>

<body>
    <main>
        <h4>Object oriented dynamic tab</h4>
        <div class="tabsbox" id="tab">
            <!-- tab label -->
            <nav class="firstnav">
                <ul>
                    <li class="liactive"><span>Test 1</span><span class="iconfont icon-guanbi"></span></li>
                    <li><span>Test 2</span><span class="iconfont icon-guanbi"></span></li>
                    <li><span>Test 3</span><span class="iconfont icon-guanbi"></span></li>
                </ul>
                <div class="tabadd">
                    <span>+</span>
                </div>
            </nav>

            <!-- tab content -->
            <div class="tabscon">
                <section class="conactive">Test 1</section>
                <section>Test 2</section>
                <section>Test 3</section>
            </div>
        </div>
    </main>
    <script src="js/tab.js"></script>
</body>
</html>

tab.js

var that;
class Tab {
    constructor(id) {
        that = this;
        // Get element
        this.main = document.querySelector(id);
        this.add = this.main.querySelector('.tabadd');
        // Parent element of li
        this.ul = this.main.querySelector('.firstnav ul:first-child');
        // Parent element of section
        this.div = this.main.querySelector('.tabscon');
        this.init();
    }

    // Initialize the operation to bind related elements to events
    init() {
        this.updateNode();
        this.add.onclick = this.addTab;
        for (var i = 0; i < this.lis.length; i++) {
            this.lis[i].index = i;
            this.lis[i].onclick = this.toggleTab;
            this.remove[i].onclick = this.removeTab;
            this.spans[i].ondblclick = this.editTab;
            this.sections[i].ondblclick = this.editTab;
        }
    }

    // 1. Switching function
    toggleTab() {
        that.clearClass();
        this.className = 'liactive';
        that.sections[this.index].className = 'conactive';
    }

    // 2. Add functions 
    addTab() {
        that.clearClass();
        // Create li element and section element
        var random = Math.random();
        var li = '<li class="liactive"><span>new tab </span><span class="iconfont icon-guanbi"></span></li>';
        var section = '<section class="conactive">' + random + '</section>';
        // Append these two elements to the corresponding parent element
        that.ul.insertAdjacentHTML('beforeend', li);
        that.div.insertAdjacentHTML('beforeend', section);
        that.init();
    }

    // 3. Delete function
    removeTab(e) {
        // Prevent bubbling (clicking delete will trigger the switching function of li)
        e.stopPropagation();
        var index = this.parentNode.index;
        console.log(index);
        // Delete the corresponding li and section according to the index number
        that.lis[index].remove(); // The remove() method can directly delete the specified element
        that.sections[index].remove();
        that.init();
        // When we delete a li that is not in the selected state, the li state of the currently selected state remains unchanged
        if (document.querySelector('.liactive')) return;
        // When we delete the selected li, if the deleted li is not the first one, the previous li will be selected
        if (index > 0) {
            index--;
        }
        // The click event is called manually without mouse triggering
        that.lis[index].click();
    }

    // 4. Modify function
    editTab() {
        // Double click to suppress the selected text
        window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty();
        // Add text box
        var str = this.innerHTML;
        this.innerHTML = '<input type="text" />';
        var input = this.children[0];
        input.value = str;
        input.select(); // The text in the text box is selected
        // When we leave the text box, we give the value in the text box to span
        input.onblur = function () {
            this.parentNode.innerHTML = this.value;
        }
        // Press enter to return the value in the text box to span
        input.onkeyup = function (e) {
            if (e.keyCode === 13) {
                // Manually invoke the form loss of focus event
                this.blur();
            }
        }
    }

    // Clear style
    clearClass() {
        for (var i = 0; i < that.lis.length; i++) {
            that.lis[i].className = '';
            that.sections[i].className = '';
        }
    }

    // When dynamically adding elements, you need to retrieve the corresponding elements
    updateNode() {
        this.lis = this.main.querySelectorAll('li');
        this.sections = this.main.querySelectorAll('section');
        this.remove = this.main.querySelectorAll('.icon-guanbi');
        this.spans = this.main.querySelectorAll('.firstnav li span:first-child');
    }
}
new Tab('#tab');

Posted by Bhaal on Wed, 24 Nov 2021 00:53:26 -0800