Table of Contents
Understanding class definition class
Similarities and differences between classes and constructors
Constructor of the class
Instance method of the class
JavaScript中的多态
Home Web Front-end Front-end Q&A Is the class class an es6 syntax?

Is the class class an es6 syntax?

Oct 21, 2022 pm 05:03 PM
javascript es6

The class class is es6 syntax and is a new feature of es6. In ES6, the class keyword was introduced to quickly define a "class", but the essence of a class is function; it can be regarded as a syntactic sugar, making the writing of object prototypes clearer and more like the syntax of object-oriented programming. Use class to define the class method "class Person{//class declaration}" or "const Person=class{//class expression}".

Is the class class an es6 syntax?

The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.

The class class is es6 syntax and is a new feature of es6.

In ES6, the class keyword was introduced to quickly define "classes".

In JS, the essence of "class" is function, which can be regarded as a syntactic sugar, making the writing method of object prototype more concise and clear, more like the syntax of object-oriented programming.

Understanding class definition class

We will find that creating a class according to the previous constructor form is not only too similar to writing an ordinary function , and the code is not easy to understand.

In the new standard of ES6 (ECMAScript2015), the class keyword is used to directly define the class; but the class is still essentially the syntax sugar of the constructor and prototype chain mentioned earlier. ;So learning the previous constructors and prototype chains will help us understand the concept and inheritance relationship of classes;

So, how to use class to define a class? –You can use two ways to declare a class: class declaration and class expression;

class Person{
    //类声明
}

const Person=class{
    //类表达式
}
Copy after login

Similarities and differences between classes and constructors

Let’s Study some characteristics of the class: you will find that it is actually consistent with the characteristics of our constructor;

console.log(Person.prototype)
console.log(Person.prototype.__proto__)//Object null 
console.log(Person.prototype.constructor)//Person
console.log(typeof Person) // function

var p = new Person()
console.log(p.__proto__ === Person.prototype) // true
Copy after login

Constructor of the class

If we want to When creating an object, you pass some parameters to the class. What should you do at this time?

  • Each class can have its own constructor (method), The name of this method is a fixed constructor;
  • When we operate through new symbol, when operating a class, the constructor constructor of this class will be called;
  • Each class can only have one constructor, if it contains multiple constructors, an exception will be thrown ;

When we operate a class through the new keyword, this constructor function will be called and the following operations will be performed:

  • 1. Create a new one in memory Object (empty object);
  • 2. The [[prototype]] attribute inside this object will be assigned to the prototype attribute of the class;
  • 3. This inside the constructor will point to The new object created;
  • 4. Execute the internal code of the constructor (function body code);
  • 5. If the constructor does not return a non-null object, the new object created is returned ;

Instance method of the class

The properties we defined above are all placed directly on this, which means that it is placed on the created In the new object:

We said before that for instance methods, we hope to put them on the prototype so that they can be shared by multiple instances; Defined in the class;

class Person {
  constructor(name, age) {
    this.name = name
    this.age = age
    this._address = "广州市"
  }

  // 普通的实例方法
  // 创建出来的对象进行访问
  // var p = new Person()
  // p.eating()
  eating() {
    console.log(this.name + " eating~")
  }

  running() {
    console.log(this.name + " running~")
  }
}
Copy after login

Accessor method of the class

When we talked about the property descriptor of the object before, we mentioned that the object can add setter and getter functions. Then classes are also possible:

class Person {
  constructor(name, age) {
    this.name = name
    this.age = age
    this._address = "广州市"
  }

  // 类的访问器方法
  get address() {
    console.log("拦截访问操作")
    return this._address
  }

  set address(newAddress) {
    console.log("拦截设置操作")
    this._address = newAddress
  }
}
Copy after login

Static methods of classes

Static methods are usually used to define methods that are executed directly using the class. There is no need for an instance of the class. Use the static keyword to define:

class Person {
  constructor(name, age) {
    this.name = name
    this.age = age
    this._address = "广州市"
  }
  // 类的静态方法(类方法)
  // Person.createPerson()
  static randomPerson() {
    var nameIndex = Math.floor(Math.random() * names.length)
    var name = names[nameIndex]
    var age = Math.floor(Math.random() * 100)
    return new Person(name, age)
  }
}
Copy after login

Inheritance of ES6 classes - extends

We have spent a lot of time discussing the implementation of inheritance in ES5. Although a relatively satisfactory inheritance mechanism was finally achieved, the process was still very cumbersome.

In ES6, the extends keyword is added, which can easily help us implement inheritance:

class Person{
    
}

class Student extends Person{
    
}
Copy after login

super keyword

We will find In the above code, I used a super keyword. This super keyword has different ways of use:

Note: Before using this in the constructor of a sub (derived) class or returning the default object, you must first pass super Call the constructor of the parent class!

There are three places where super can be used: constructors of subclasses, instance methods, and static methods;

Is the class class an es6 syntax? ##Inherit built-in classes

We can also let our classes inherit from built-in classes, such as Array:
class HYArray extends Array {
  firstItem() {
    return this[0]
  }

  lastItem() {
    return this[this.length-1]
  }
}

var arr = new HYArray(1, 2, 3)
console.log(arr.firstItem())
console.log(arr.lastItem())
Copy after login

Class mixin

JavaScript classes only support single inheritance: that is, there can only be one parent class

. So when we need to add more similar functions to a class during development, how should we do it? At this time we can use mixin;

JavaScript中的多态

面向对象的三大特性:封装、继承、多态

前面两个我们都已经详细解析过了,接下来我们讨论一下JavaScript的多态。JavaScript有多态吗?

维基百科对多态的定义:多态(英语:polymorphism)指为不同数据类型的实体提供统一的接口,或使用一

个单一的符号来表示多个不同的类型。

非常的抽象,个人的总结:不同的数据类型进行同一个操作,表现出不同的行为,就是多态的体现。

那么从上面的定义来看,JavaScript是一定存在多态的。

// 多态: 当对不同的数据类型执行同一个操作时, 如果表现出来的行为(形态)不一样, 那么就是多态的体现.
function calcArea(foo) {
  console.log(foo.getArea())
}

var obj1 = {
  name: "why",
  getArea: function() {
    return 1000
  }
}

class Person {
  getArea() {
    return 100
  }
}

var p = new Person()

calcArea(obj1)
calcArea(p)

// 也是多态的体现
function sum(m, n) {
  return m + n
}

sum(20, 30)
sum("abc", "cba")
Copy after login
// 传统的面向对象多态是有三个前提:
// 1> 必须有继承(是多态的前提)
// 2> 必须有重写(子类重写父类的方法)
// 3> 必须有父类引用指向子类对象

// Shape形状
class Shape {
  getArea() {}
}

class Rectangle extends Shape {
  getArea() {
    return 100
  }
}

class Circle extends Shape {
  getArea() {
    return 200
  }
}

var r = new Rectangle()
var c = new Circle()

// 多态: 当对不同的数据类型执行同一个操作时, 如果表现出来的行为(形态)不一样, 那么就是多态的体现.
function calcArea(shape: Shape) {
  console.log(shape.getArea())
}

calcArea(r)
calcArea(c)

export {}
Copy after login

【相关推荐:javascript视频教程编程视频

The above is the detailed content of Is the class class an es6 syntax?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data

See all articles