ECMAScript 6 Tutorials (iii) class and module (classes and modules)

Source: Internet
Author: User

This article is copyright to the author and the blog Park, Welcome to reprint, but without the consent of the author must retain this paragraph of the statement, and in the article page obvious location to the original link, blog address is http://www.cnblogs.com/jasonnode/. This series of courses is compiled by Hui Zhi Network, the course address is http://www.hubwiz.com/course/5594e91ac086935f4a6fb8ef/

Class
    1. Class Basic syntax
    2. Inheritance of Class
    3. class's accessor (getter) and stored-value function (setter)
    4. The generator method of class
    5. static method of Class
    6. New.target Property
    7. Decorator
Module
    1. Export command
    2. Import command
    3. Overall input of the module
    4. Module command
    5. Export default command
    6. Inheritance of modules
Class Basic syntax

ES6 provides a more similar approach to traditional languages, introducing the concept of class as a template for objects. You can define classes by using the class keyword.

 //  define class    point {Constructor (x, y) { this        . x = X;      Y; } toString () { return   "  (  +this . X+ '   "  + This . Y+ " )       

The above code defines a "class", and you can see that there is a constructor method in it, which is the constructor method, and the This keyword represents the instance object.

Constructor method

The constructor method is the default method for the class, which is called automatically when an object instance is generated from the new command.

Instance Object
var New Point (2, 3);
Name property
// "Point"
Class-expression

As with functions, class can also be defined in the form of an expression.

Const MYCLASS = class Me {    getclassname () {        return  me.name;    }};
Inheritance of Class

Class can be inherited through the extends keyword.

Subclasses inherit the properties and methods of the parent class.

class Point {    constructor (x, y) {        this. x = x;          this. y = y;    }} class ColorPoint extends Point {    constructor (x, y, color) {        this
    //  referenceerror        super (x, y);          This // correct     }}            

In the above code, the subclass's constructor method does not call super before using the This keyword, the result is an error, and the Super method is right after it is placed.

Note: ColorPoint inherits the parent class point, but its constructor must call the Super method.

The following is the code that generates the subclass instance.

New ColorPoint (8, ' green 'instanceof//  trueinstanceof//  True
class's accessor (getter) and stored-value function (setter)

Within class, you can use the GET and set keywords to set the stored-value and accessor functions on a property.

class MyClass {get prop () {  return ' getter '; } set Prop (value) {document.write (' setter: ' +new= 123; // setter:123 Inst.prop // ' getter '
The generator method of class

If a method is preceded by an asterisk (*), it means that the method is a generator function.

class Foo {    constructor (... args) {        this. args = args;    }      * [Symbol.iterator] () {        for this. args) {            yield arg;        }      for New Foo (' Hello ', ' world '){    document.write (x);} // Hello // World        

In the above code, the Symbol.iterator method of the Foo class has an asterisk before it, indicating that the method is a generator function. The Symbol.iterator method returns the default walker for a Foo class, and the For...of loop automatically calls the walker.

In the above code, the prop attribute has a corresponding stored value function and accessor, so the assignment and read behavior are customized.

static method of Class

Class is equivalent to the prototype of an instance, and all methods defined in the class are inherited by the instance. If you precede a method with the static keyword, it means that the method is not inherited by the instance, but instead is called directly through the class, which is called a "static method."

class Foo {    static classmethod () {        return ' Hello ';     // ' Hello ' var New Foo (); Foo.classmethod () // typeerror:undefined is not a function

In the above code, the Classmethod method of the Foo class has the static keyword, indicating that the method is a static method that can be called directly on the Foo class (Foo.classmethod ()) rather than on an instance of the Foo class. If a static method is called on an instance, an error is thrown indicating that the method does not exist.

The static method of the parent class, which can be inherited by the quilt class.

class Foo {    static classmethod () {        return ' Hello ';     // ' Hello '

In the above code, the parent class Foo has a static method, and the subclass bar can call this method.

Static methods can also be called from a Super object.

class Foo {    static classmethod () {        return ' Hello ';    }} Class Bar extends Foo {    static classmethod () {        return super.classmethod () + ', too ';    }} Bar.classmethod ();
New.target Property

New is a command that generates an instance from a constructor. ES6 introduces a New.target property for the new command, (in the constructor) that returns the constructor that the new command is used for. If the constructor is not called by the new command, New.target returns undefined, so this property can be used to determine how the constructor is called.

functionPerson (name) {if(New. Target!==undefined) { This. Name =name; } Else{Throw NewError (' must use new build instance '); }} //Another way of writingfunctionPerson (name) {if(New. target = = =Person ) { This. Name =name; } Else{Throw NewError (' must use new build instance '); }} varperson =NewPerson (' Zhang San ');//correctvarNotaperson = Person.call (person, ' Zhang San ');//Error

The above code ensures that the constructor can only be called by the new command.

    • The class internally calls New.target, returning the current class.
    • When a subclass inherits from a parent class, New.target returns a subclass.
Decorator

A decorator (Decorator) is an expression used to modify the behavior of a class.

The Decorator function can accept three parameters, followed by the target function, the property name, and the description object of the property. The latter two parameters can be omitted. In the above code, the parameter target of the testable function is the object to be decorated. If you want the decorator's behavior to be different depending on the target object, you need to encapsulate a layer of functions outside.

function testable (istestable) {returnfunction= istestable;}} @testable (true//  true  @testable (false  // false

If you want to add a method to an instance of a class, you can add a method to the prototype property of the target class in the Decorator function.

function testable (target) {    truenew//  true
Export command

The module functions are composed of two commands: Export and import.

    • Export command for user-defined module, specify external interface;
    • The import command is used to enter functionality provided by other modules while creating namespaces (namespace) to prevent function name collisions.

ES6 allows separate JS files to be used as modules, allowing a JavaScript script file to invoke another script file.

An existing Profile.js file that holds the user information. ES6 treats it as a module, which outputs three variables externally with the Export command.

// Profile.js var firstName = ' Michael '; var lastName = ' Jackson '; var year = 1958; export {firstName, lastName, year};
Import command

After using the export command to define the external interface of the module, other JS files can be loaded with the import command (file).

// main.jsImport {firstName, lastName, year} from './profile 'function= FirstName + "+ LastName;}

The above code belongs to another file, and the Main.js,import command is used to load the Profile.js file and enter the variable from it. The import command accepts an object (expressed in curly braces), which specifies the name of the variable to import from the other module. The variable name inside the curly brace must be the same as the name of the external interface of the imported module (profile.js).

If you want to re-name the input variable, use the AS keyword in the import statement to rename the input variable.

Import {LastName as surname} from './profile ';

The ES6 supports multiple loads, which load other modules in the loaded module.

Overall input of the module

The export command can also output a method or Class (class) In addition to the output variable. Below is a circle.js file that outputs two methods area and circumference.

// Circle.js function Area (RADIUS) {  return Math.PI * radius *function  circumference (radius) {  C8>return 2 * Math.PI * radius;}

Then, Main.js enters the Circlek.js module.

// main.jsImport {area, circumference} from ' Circle ';d ocument.write ("Circle Size:" + areas (4)); document.write ("circumference length:" + circumference (14));

The above notation specifies the method to be entered. Another way of writing is the overall input.

Import * as circle from ' Circle ';d ocument.write ("Circle area:" + Circle.area (4));d Ocument.write ("circumference length:" + Circle.circumference (14));
Module command

The module command can replace the import statement to achieve the function of the overall input module.

// main.jsmodule circle from ' Circle '; document.write ("Circle area:" + Circle.area (4));d Ocument.write ( "Circumference Length:" + circle.circumference (14));

The module command is followed by a variable, which indicates that the input modules are defined on the variable.

Export default command

Specify the default output for the load module, using the Export default command.

// Export-default.js default function () {document.write (' foo ');}

The above code is a module file Export-default.js, and its default output is a function.

When other modules load the module, the import command can specify any name for the anonymous function.

// import-default.jsimport customname from './export-default '//  ' foo '

The import command for the above code can point to the method of export-default.js output with any name. It is important to note that no curly braces are used after the import command.

Inheritance of modules

Can also inherit between modules.

Suppose you have a Circleplus module that inherits the Circle module.

// Circleplus.js  * from ' Circle 'var e = 2.71828182846defaultfunction(x) { /c10>return  math.exp (x);}

The "Export *" in the above code, which represents all the properties and methods of the output circle module, defines the default method for the module.

At this point, you can also rename the circle's properties or methods and then output it.

// Circleplus.js  ' Circle ';

The above code indicates that only the area method of the Circle module is output and renamed to Circlearea.

The above module is loaded with the following notation.

// Main.js  "Circleplus""Circleplus";d ocument.write (exp (Math.PI));

The "Import exp" in the above code means that the default method of the Circleplus module is loaded as the Exp method.

ECMAScript 6 Tutorials (iii) class and module (classes and modules)

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.