The use of class in JavaScript ES6 _javascript tips

Source: Internet
Author: User
Tags es6 class

Objective

For JavaScript, classes are optional (not necessarily) design patterns, and implementing classes in [[Prototype]] languages like JavaScript is lame.

This kind of lame feeling is not just from grammar, although grammar is a very important reason. JS has a lot of grammatical shortcomings: cumbersome and messy. Prototype refers to explicit pseudo polymorphism when attempting to invoke a function of the same name on the upper layer of the prototype chain and is unreliable, unattractive, and easily misunderstood as a "constructor". Constructor.

In addition, there are further problems in class design. The parent class and subclasses, subclasses, and instances in a traditional class-oriented language are actually copy operations, but they are not replicated in [[Prototype]].

The object Association code and the Behavior delegate use [[Prototype]] instead of hiding it, as you can see from the simplicity of the class that it does not apply to JavaScript.

The use of class in ES6

The JavaScript tradition is that when you build an object instance, you need to define the constructor and then do it in new way.

function Stdinfo () {
  this.name = ' job ';      
  This.age = n      
}

StdInfo.prototype.getNames = function () {
  console.log ("Name:" +this.name);        
}
Get a Student Information object
var p = new Stdinfo ()

There are only objects in the Javacript, no classes. It is a prototype language, and the prototype object is the template for the new object, which shares its own attributes to the new object. This kind of writing and the traditional object-oriented language is very different, it is easy to confuse novice.

Defining classes

To the ES6 added class, as the object template. Define a class by class:

Defines class
Stdinfo {
  constructor () {
    this.name = "job";      
    This.age = n   
  }
  Methods defined in a class do not need to add a function
  GetNames () {
    console.log ("Name:" +this.name);   
  }
Use new method to get an instance object
var p = new Stdinfo ();

The above wording is clearer, more like object-oriented programming syntax, and seems easier to understand.

The class that is defined is just a syntactic sugar, which is intended to create objects and handle related inheritance in a more concise and straightforward syntax.

Define class
Stdinfo {
  //...
}
Console.log (typeof Stdinfo); function

Console.log (stdinfo = = = StdInfo.prototype.constructor);//true

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

Functions are defined in terms of function declarations and function expressions, and classes are defined in two ways: class declarations and class expressions.

class declaration

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

Define class, you can omit constructor
class Stdinfo {
  getNames () {
    console.log ("Name:" +this.name);
  }
-------------------------------------
///Definition class, add constructor
class Stdinfo {
  ////////////////// Incoming parameter
  constructor (name,age) {
    this.name = name;      
    This.age = age;   
  }
  
  GetNames () {
    console.log ("Name:" +this.name);   
  }
When defining an instance object, pass in the argument
var p = new Stdinfo ("job", 30)

constructor is a default method that uses new to define an instance object, automatically executes the constructor function, passes in the required parameters, and automatically returns the instance object when the constructor is finished.

There can be only one constructor function in a class, and multiple errors can be defined.

The this in constructor points to the newly created instance object, using this to extend the properties to the newly created instance object.

When you define an instance object, you do not need to do something in the initialization phase, and you do not have to display the write constructor function. If there is no explicit definition, an empty constructor method is added by default, constructor () {}

-Class expressions

A class expression is another form of defining a class, similar to a function expression, that assigns a function as a value to a variable. You can assign a defined class to a variable, and the variable is the class name. The class name is not optional, and can only be used within the class if it exists.

Define class class after class name:

Const PEOPLE = class Stdinfo {
  constructor () {
    console.log (stdinfo);//can print out values, is a function
  }

New people ();
New Stdinfo (); Error, Stdinfo is not defined;

There are no class names following the definition class class:

Const PEOPLE = class {
  constructor () {

  }
}

new People ();

Classes to execute immediately:

Const P = new Class {
  constructor (name,age) {
    console.log (name,age);
  }
} ("Job", 30)

class to be executed immediately, add new before the class. P is an instance object of the class.

There is no variable elevation

The definition class does not have a variable elevation, it can only be used after the class is defined, and differs from the function declaration.

-----function declaration-------
//definition can be used first, because the function declaration is promoted, the invocation is legitimate.
func ();
function func () {}

//-----definition Class---------------
new Stdinfo ();//error, Stdinfo is not defined
class stdinfo{}

Extends inheritance

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

Defines class parent
{
  Constructor (name,age) {
    this.name = name;
    This.age = age;
  }

  Speaksometing () {
    console.log ("I can speek Chinese");
  }
Define subclasses, inheriting parent class child
extends Parent {
  coding () {
    Console.log ("Coding JavaScript");
  }

var C = new Child ();

You can call the parent class's method
c.speaksometing ()//I can speek Chinese

By using inheritance, subclasses have the method of the parent class.

If there are constructor constructors in subclasses, you must use call super.

Defines class parent
{
  Constructor (name,age) {
    this.name = name;
    This.age = age;
  }

  Speaksometing () {
    console.log ("I can speek Chinese");
  }
Defines a subclass, inherits the parent class child
extends Parent {
  Constructor (name,age) {
    //does not tune super (), then the error is not defined

    //Must call Super
    super (name,age);
  }

  Coding () {
    Console.log ("Coding JavaScript");
  }

var C = new Child ("job");

You can call the parent class's method
c.speaksometing ()//I can speek Chinese

Subclasses must call the Super method in the constructor method, or the new instance will have an error (this isn't defined). This is because the subclass does not have its own this object, but instead inherits the this object of the parent class and then processes it. If you do not call the Super method, the subclass will not get the This object.

Summarize

Well, the above is a simple summary of the ES6 class of learning, I hope the content of this article for everyone's study or work can bring some help, if there is doubt you can message exchange, thank you for your support cloud habitat community.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.