JS quickly master ES6 class usage

JS quickly master ES6 class usage

1. How to construct?

Let's review the common methods of building classes in es5: First of all, es5 uses prototypes for object methods, so why not add methods in the constructor? Because when instantiating an object, many identical methods will be repeatedly created, wasting resources. So you need to mount the object's method into prtotype.

Regarding the binding problem of new and this, it can be roughly simplified as follows:

  • First, create a new object through new
  • Then bind this object to the this of the constructor
  • Then bind the prototype object of this constructed object
  • Finally, return this object to the previously defined object

So let’s look at an example:

function Animal(name,age){
  this.name = name
  this.age = age
  
  // This is a waste of resources // this.eat = function(){
  // console.log("I had dinner today")
  // }
}

// Correct approach Animal.prototype.eat=function(){
  console.log("I had dinner today")
}

Then use ES6 class, which obviously simplifies this operation.

const dog = new Animal("wangcai",2) // Will report an error. In order to correct bad habits, ES6, like let and const, will not promote class.

class Animal{
  constroctor(name,age){
    this.name = name 
    this.age = age 
  }
  
    eat(){
    console.log("I had dinner today")
  }
}

cosnt dog = new Animal("wangcai",2) //correct position

In addition, the class also adds static methods, set, get and other operations.

class Animal{
  constroctor(name,age){
    this.name = name 
    this.age = age 
  }
  
    eat(){
    console.log("I had dinner today")
  }
  

 set name(value){
    this.tempname = "Lao Tie" + value
  }
  
  get name(){
    return this.tempname
  }
  
  static introuduce(){
    console.log("I am now an animal class")
  }
}

//set() get()
const dog = new Animal("giao",2)
dog.name="agiao" 
console.log(dog.name) // Laotieagiao

// Static method Animal.introuduce() // I am now an animal class

Before we talk about inheritance, let me add a little knowledge point. The method name of the class can be named by calculating the attribute operation.

let tempname = "giao"
class Animal{
   constroctor(name,age){
    this.name = name 
    this.age = age 
  }
  
  [tempname](){
    console.log("Give me a giao")
  }
}

const xiaoagiao = new Animal("giaoge",30)
xiaoagiao.giao() // Give me a giao

2. Inheritance

Back to the question of inheritance, how does es5 inherit?

function Animal( name ){
  this.name = name
}
Animal.prototype.break(){
  console.log("scream!")
}

function Dog( name, age ){
  Animal.call(this,name)
  this.age = age
}

Dog.prototype = new Animal()
Dog.prototype.constructor = Dog

So this is called composition inheritance, how is it combined?

The inheritance of properties is borrowed inheritance. You can see that Animal.call(this,name) is equivalent to calling the Animal function once in the Dog constructor. Although the properties are not linked in the prototype chain, the code is run on Dog, so it naturally inherits the name property of Animal.

Animal.call(this,name)

The inheritance of methods is prototype inheritance. As we all know, a function will generate a prototype object when it is created. The prototype property of this function points to its prototype object, and the constructor property of the prototype object points to this function. If you use new to create a new instance of this function, this instance will have a __proto__ property pointing to the prototype object of the function. Therefore, by borrowing the function instance, we will point to the function prototype object. We will instantiate the inherited function and then assign the instantiated object to the prototype property of the inherited constructor, thus forming a chain structure. But the inherited function instantiation does not have the constructor attribute, so we need to point its constructor to the inherited constructor.

Dog.prototype = new Animal()
Dog.prototype.constructor = Dog

So according to this routine, we use es5 syntax to inherit the name and break methods of the Animal function from the dog function.

So how does ES6 do it?

class Animal{
  constructor( name ){
    this.name = name 
  }
  
  break(){
    console.log("scream!")
    }
}

class Dog extends Animal {
  constructor( name, age ){
    super(name)
    this.age=age
  }
}

Now you just need to add an extends Animal when declaring the Dog class, and then add a super in the constructor.

This super(name) is equivalent to Animal.call(this,name). As for the method problem, you don't have to worry about it. The extends function will automatically handle it, so you don't have to use prototype to point to it.

The above is the detailed content of how to quickly master the usage of ES6 class in JS. For more information about the usage of JS ES6 class, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • js learning notes: class, super and extends keywords
  • JavaScript object-oriented class inheritance case explanation
  • Two ways to write JS tab plugins (jQuery and class)
  • Detailed explanation of adding and deleting class names using JS
  • Class in front-end JavaScript

<<:  Apache Spark 2.0 jobs take a long time to finish when they are finished

>>:  MySQL performance comprehensive optimization method reference, from CPU, file system selection to mysql.cnf parameter optimization

Recommend

WML tag summary

Structure related tags ---------------------------...

Mysql join table and id auto-increment example analysis

How to write join If you use left join, is the ta...

Solution to Vue data assignment problem

Let me summarize a problem that I have encountere...

jQuery plugin to implement minesweeper game (2)

This article shares the second article of using j...

MySQL encoding utf8 and utf8mb4 utf8mb4_unicode_ci and utf8mb4_general_ci

Reference: MySQL character set summary utf8mb4 ha...

XHTML Getting Started Tutorial: XHTML Web Page Image Application

<br />Adding pictures reasonably can make a ...

Implementation code of using select to select elements in Vue+Openlayer

Effect picture: Implementation code: <template...

Comparison of the advantages of vue3 and vue2

Table of contents Advantage 1: Optimization of di...

Two methods to stretch the background image of a web page

There are two solutions: One is CSS, using backgro...

js implements a simple English-Chinese dictionary

This article shares the specific code of js to im...

TCP socket SYN queue and Accept queue difference analysis

First we must understand that a TCP socket in the...

Example code for css flex layout with automatic line wrapping

To create a flex container, simply add a display:...

How to draw a vertical line between two div tags in HTML

Recently, when I was drawing an interface, I enco...