Home > Web Front-end > JS Tutorial > Detailed explanation of the use of CLASS in JavaScript ES6

Detailed explanation of the use of CLASS in JavaScript ES6

高洛峰
Release: 2016-12-06 09:30:56
Original
1709 people have browsed it

Foreword

For JavaScript, classes are an optional (but not required) design pattern, and it is very lame to implement classes in [[Prototype]] languages ​​like JavaScript.

This lame feeling doesn’t just come from grammar, although grammar is a very important reason. There are many grammatical shortcomings in js: cumbersome and messy .prototype references, explicit pseudo-polymorphism when trying to call functions of the same name on the upper level of the prototype chain, and .constructor that is unreliable, unsightly and easily misunderstood as a "constructor".

In addition, there are actually further problems in class design. In traditional class-oriented languages, there is actually a copy operation between parent class and subclass, subclass and instance, but there is no copying in [[Prototype]].

Object association code and behavior delegation use [[Prototype]] instead of hiding it. Compared with its simplicity, it can be seen that classes are not suitable for JavaScript.

The use of CLASS in ES6

The traditional way of using JavaScript is that when generating an object instance, you need to define a constructor and then complete it through new.

function StdInfo(){
  this.name = "job";     
  this.age = 30;     
}
 
StdInfo.prototype.getNames = function (){
  console.log("name:"+this.name);       
}
//得到一个学员信息对象
var p = new StdInfo()
Copy after login

There are only objects in JavaScript, not classes. It is a prototype-based language. The prototype object is the template of a new object, and it shares its own properties with the new object. This way of writing is very different from traditional object-oriented languages, and it can easily confuse novices.

Define classes

In ES6, classes were added as templates for objects. Define a class through class:

//定义类
class StdInfo {
  constructor(){
    this.name = "job";     
    this.age = 30;  
  }
  //定义在类中的方法不需要添加function
  getNames(){
    console.log("name:"+this.name);  
  }
}
//使用new的方式得到一个实例对象
var p = new StdInfo();
Copy after login

The above writing is clearer, more like the syntax of object-oriented programming, and it seems easier to understand.

The defined classes are just syntactic sugar, which allows us to create objects and handle related inheritance in a more concise and clear syntax.

//定义类
class StdInfo {
  //...
}
console.log(typeof StdInfo); //function
 
console.log(StdInfo === StdInfo.prototype.constructor); //true
Copy after login

As can be seen from the above test, the type of the class is a function, a "special function" that points to the constructor.

There are two ways to define functions: function declaration and function expression. There are also two ways to define classes: class declaration and class expression.

Class declaration

A class declaration is a way of defining a class, using the keyword class, followed by the class name, and then a pair of curly brackets. Put the methods that need to be defined in curly brackets.

//定义类,可以省略constructor
class StdInfo {
  getNames(){
    console.log("name:"+this.name);
  }
}
// -------------------------------------
//定义类,加上constructor
class StdInfo {
  //使用new定义实例对象时,自动调用这个函数,传入参数
  constructor(name,age){
    this.name = name;     
    this.age = age;  
  }
   
  getNames(){
    console.log("name:"+this.name);  
  }
}
//定义实例对象时,传入参数
var p = new StdInfo("job",30)
Copy after login

constructor is a default method. When using new to define an instance object, the constructor function is automatically executed, the required parameters are passed in, and the instance object is automatically returned after executing the constructor.

There can only be one constructor function in a class. If you define more than one, an error will be reported.

This in the constructor points to the newly created instance object, use this to extend properties to the newly created instance object.

When defining an instance object, you don’t need to do anything in the initialization phase, and you can write the constructor function without displaying it. If not explicitly defined, an empty constructor method will be added by default, constructor(){}

Class expression

Class expression is another form of defining a class, similar to a function expression, taking a function as The value is assigned to the variable. You can assign the defined class to a variable, in which case the variable is the class name. The class name after the class keyword is optional. If present, it can only be used within the class.

Define a class with a class name after it:

const People = class StdInfo {
  constructor(){
    console.log(StdInfo); //可以打印出值,是一个函数
  }
}
 
new People();
new StdInfo(); //报错,StdInfo is not defined;
Copy after login

There is no class name after a definition class:

const People = class {
  constructor(){
 
  }
}
 
new People();
Copy after login

Immediately executed class:

const p = new class {
  constructor(name,age){
    console.log(name,age);
  }
}("job",30)
Copy after login

class, in Add new before the class. p is an instance object of the class.

There is no variable promotion

There is no variable promotion when defining a class. You can only define the class first and then use it, which is different from function declaration.

//-----函数声明-------
//定义前可以先使用,因为函数声明提升的缘故,调用合法。
func();
function func(){}
 
//-----定义类---------------
new StdInfo(); //报错,StdInfo is not defined
class StdInfo{}
Copy after login

EXTENDS inheritance

Use the extends keyword to implement inheritance between classes. This is much more convenient than using inheritance in ES5.

//定义类父类
class Parent {
  constructor(name,age){
    this.name = name;
    this.age = age;
  }
 
  speakSometing(){
    console.log("I can speek chinese");
  }
}
//定义子类,继承父类
class Child extends Parent {
  coding(){
    console.log("coding javascript");
  }
}
 
var c = new Child();
 
//可以调用父类的方法
c.speakSometing(); // I can speek chinese
Copy after login

Using inheritance, the subclass has the methods of the parent class.

If there is a constructor in the subclass, you must use super.

//定义类父类
class Parent {
  constructor(name,age){
    this.name = name;
    this.age = age;
  }
 
  speakSometing(){
    console.log("I can speek chinese");
  }
}
//定义子类,继承父类
class Child extends Parent {
  constructor(name,age){
    //不调super(),则会报错 this is not defined
 
    //必须调用super
    super(name,age);
  }
 
  coding(){
    console.log("coding javascript");
  }
}
 
var c = new Child("job",30);
 
//可以调用父类的方法
c.speakSometing(); // I can speek chinese
Copy after login

The subclass must call the super method in the constructor method, otherwise an error (this is not defined) will be reported when creating a new instance. This is because the subclass does not have its own this object, but inherits the this object of the parent class and then processes it. If the super method is not called, the subclass will not get this object.


Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template