Home  >  Article  >  Web Front-end  >  What does es6 class do?

What does es6 class do?

青灯夜游
青灯夜游Original
2022-10-26 18:49:432184browse

The class keyword of es6 is used to quickly define a "class"; the essence of class is function, which can be regarded as a syntactic sugar, making the writing of object prototypes clearer and more like the syntax of object-oriented programming. There is no variable promotion when promoting a class. All methods of a class are defined on the prototype attribute of the class. Calling a method on an instance of a class is actually calling a method on the prototype.

What does es6 class do?

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

Basics

  • es6 introduces the concept of Class. The class keyword is used to quickly define a "class". The new class writing method makes the writing of object prototypes clearer, more like the syntax of object-oriented programming, and easier to understand.

  • In fact, the concepts of prototype and constructor are still used behind it.

  • Strict mode There is no need to use use strict because as long as the code is written within classes and modules, strict mode can only be used.

  • There is no variable promotion when improving class (due to inheritance, you must ensure that the subclass is defined after the parent class).

  • All methods of a class are defined on the prototype attribute of the class. Calling methods on instances of the class is actually calling methods on the prototype. Prototype methods can be called through instance objects, but not When calling through the class name, an error will be reported

class is used to define a class for es6
  • In fact, class is just a Syntax sugar is another way of writing constructor

  • (Syntax sugar is an elegant solution at the syntax level to avoid coding errors and improve coding efficiency. Simply put, it is portable. Just writing method)

Look at the code

class Person{
}
console.log(typeof Person)                               //funciton
console.log(Person.prototype.constructor === Person)     //true

Use and look at the code
The usage is the same as using the constructor. Use new to generate object instances

class person2 {
}
let json = new person2;
Properties and methods

The properties and methods defined in the constructor are instance properties and methods that are called on this, otherwise they are prototype properties and methods

class Person {
  constructor (name) {
    this.name = name            //constructor内定义的方法和属性是实例对象自己的,
  }
  say () {                      //而constructor外定义的方法和属性则是所有实例对象可以共享的 注意!
    console.log('hello')
  }
}
let jon = new Person()
jon.hasOwnPrototype('name')     //true
jon.hasOwnPrototype('say')      //false

Static methods

Methods that can be called directly through the class without passing the instance object, where this points to the class itself

class Person {
  static doSay () {
    this.say()
  }
  static say () {
    console.log('hello')
  }
}
Person.doSay()              //hello
***********************************************************************************************
//静态方法可以被子类继承
class Sub extends Person { 
}
Sub.doSay() // hello

//静态方法可以通过类名调用,不能通过实例对象调用,否则会报错
class Person {
    static sum(a, b) {
        console.log(a + b)
    }
}
var p = new Person()
Person.sum(1, 2)  // 3
p.sum(1,2)        //  TypeError p.sum is not a function

name attribute

## The #name attribute returns the name of the class, which is the name immediately following class.

class Person {
}
Person.name // Person

this defaults to an instance of the class.

If there is this inside a class method, an error is likely to be reported if this method is used alone

If this points to the wrong direction 1. Use the arrow function 2. Bind it in the constructor this

Value function (getter) and storage function (setter)
class Person {
  get name () {
    return 'getter'
  }
  set name(val) {
    console.log('setter' + val)
  }
}

let jon = new Person()
jon.name = 'jon' // setter jon
jon.name         // getter

//Class declaration cannot be repeated

class Person {}

class Person {}
// TypeError Identifier 'Person' has already been declared

constructor keyword

    Constructor method
  • The constructor method is the default method of the class. When an object instance is generated through the new command, this method is automatically called (the instance object this is returned by default).
  • A class must have a constructor method. If it is not explicitly defined, an empty constructor method will be added by default.
  • A class can only have one special method named "constructor". If the class contains multiple constructor methods, a SyntaxError will be thrown.
  • class Person {
       constructor(x, y) {
        this.x = x    //默认返回实例对象 this
        this.y = y
      }
      toString() {
        console.log(this.x + ', ' + this.y)
      }
    }

What is constructor?

Each class must have a constructor. If there is no explicit declaration, the js engine will automatically add an empty constructor

class person3 {
}
//等于 
class person3 {
    constructor(){}
}

Attention When declaring a method in a class, do not add the function keyword before the method Do not separate methods with commas, otherwise an error will be reported All methods defined inside the class are non-enumerable

Note that the attributes of the instance are the same as es5 unless they are explicitly defined on itself (i.e. this object). Defined on the prototype

class Point {
  constructor(x,y){
    this.x = x;
    this.y = y;
    
  }
  toString(){
    return `this.x + this.y`;
  }
}
var point = new Point();
point.toString()    //(2,3)
point.hasOwnProperty("x")        //true
point.hasOwnProperty("y")        //true   在这x&&y都是实例对象point自身的属性(因为定义在this变量上) // 所以返回true 
point.hasOwnProperty("toString") //false  toString是原型对象的属性 (因为定义在Point类上)             //所以返回false 
point._proto_.hasOwnProperty("toString") //true  

//加两个实例 
var p1 = new Point();
var p2 = new Point();
p1._proto_ === p2._proto_                //true    这个不建议使用 
//上面代码中 p1和p2 都是point的实例 他们的原型都是Point.prototype 所以 _proto_属性是相等的 
//即是说 可以通过实例的_proto_ 属性为 "类" 添加方法

super keyword

The super keyword is used to access and call functions on the parent class. You can also call the constructor of the parent class. Ordinary functions of the parent class

 class Father {
        constructor (surname){
            this.surname = surname
        }
        say(){
            console.log("你的名字" + this.surname)  //你的名字锤子
        }
    }
    //在这里 子继承父类
    class Son extends Father {
        constructor(surname,name){
            super(surname)
            this.name = name 
        }
        say(){
            super.say()
            console.log('调用普通' + this.name)    //调用普通铁的
        }
    }
    var son = new Son('锤子',"铁的")
    son.say()
    console.log(son)   //打印  {surname: "锤子", name: "铁的"
    //在子类的构造函数如果使用 super 调用父类的构造函数 必须写在 this之前  
    //还可以 调用父类的普通方法 
    //在es6中 类没变量提升 必须先定义 才能通过实例化对象类里面的 共有属性 和方法 通过this 调用
    //类 里面的this 代表什么
    //constructor 里面this指向实例对象  
    // 方法里面this 代表 方法的 调用者

extends inheritance

Inheritance means that the son inherits the father's business. In reality, the subclass in the program can inherit some methods and attributes from the parent class

A major feature of object-oriented inheritance can reduce the writing of code and facilitate the extraction of public content keywords extends

 class Father {
        constructor (surname){
            this.surname = surname
        }
        say(){                                     //父级Father里面有一个方法 say()  
            console.log("你的名字" + this.surname)
        }
    }

    class Son extends Father {                     //在这里Son 继承了 Father父级里面的方法   关键字extends 
    }

    var son = new Son('锤子')                      //new 出来实例   
    son.say()                                      //打印  你的名字锤子

类的方法

class Person  {
         constructor(name, age) {    
    // 构造函数,接收一个name和age
             this.name = name
             this.age = age 
         }
         say(){
    // 一个方法  //注意类里面的方法不加function关键字  方法与方法之间不用,号隔开 
             console.log("你好",this.name)
         }
         // ....sayWhat(){} saySome(){}
    }
     var person  = new Person('老王',44)
    //调用方法
     person.say()  //老王
    //在类的实例上调用方法 其实就是调用 原型上的方法

类的表达式

与函数一样 calss 也可以使用表达式的形式定义  采用class表达式 可以写出立即执行的Class!!
注意与函数表达式类似 类表达式在他们被求值前也不能使用(即赋值变量 之前调用) 但 与函数定义不同 虽然函数声明可以提升 但类不能

类表达式(类定义)
类表达式可以是被命名的或匿名的

匿名类

let Person = class {
  constructor(x, y) {
    this.x = x
    this.y = y
  }
}

命名的类

let Person = class Person {
  constructor(x, y) {
    this.x = x
    this.y = y
  }
}
const Mycalss = class Me {
    getClassName(){
        return Me.name;
    }
};     //这里用 表达式(即赋值变量一个) 
       //注意! 这个类的名字是Mycalss而不是 Me Me只在Class的内部代码可用 指代当前类
let inst = new Mycalss();
inst.getClassName()   //Me   
Me.name               //报错  Me只在Class内部有定义

采用class表达式 可以写出立即执行的Class!!

let person = new class {
    constructor(name) {
       this.name = this.name; 
    }    
    sayname(){
        console.log(this.name);
    }
}("常东东")         //这段代码中class是立即执行的实例

补充案例

class Animal {                       //class定义了一个“类”
        constructor(){
            this.type = 'animal'     //有一个constructor方法,这就是构造方法   //this关键字则代表实例对象
        }                            //constructor内定义的方法和属性是实例对象自己的,而constructor外定义的方法和属性则是所有实例对象可以共享的 注意!
        says(say){
            console.log(this.type + ' says ' + say)
        }
    }
    let animal = new Animal()
    animal.says('hello')    //animal says hello

    class Cat extends Animal {       //通过extends关键字实现继承  //定义了一个Cat类,该类通过extends关键字,继承了Animal类的所有属性和方法。
        constructor(){
            super()                  //super关键字 它指代父类的实例(即父类的this对象)子类必须在constructor方法中调用super方法,否则新建实例时会报错。
            this.type = 'cat'        //这是因为子类没有自己的this对象,而是继承父类的this对象,然后对其进行加工。如果不调用super方法,子类就得不到this对象。   
        }
    }
    let cat = new Cat()
    cat.says('hello')       //cat says hello

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

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

Statement:
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