Es6 notes 7 ^_^ class, es6 notes 7 class

Source: Internet
Author: User
Tags es6 class

Es6 notes 7 ^_^ class, es6 notes 7 class

ES6 provides a method closer to the traditional language, introducing the concept of Class as an object template. You can use the class keyword to define a class.

Part from JavaScript ES6 class guide, mozilla https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Classes
1. Define a class
Let's look back at how to define a class in ES5. Through the Object. defineProperty method that is not commonly used, I can define some read-only attributes.
function Vehicle1(make, year) {    Object.defineProperty(this, 'make', {        get: function() { return make; }    });    Object.defineProperty(this, 'year', {        get: function() { return year; }    });}Vehicle1.prototype.toString = function() {    return this.make + ' ' + this.year;}var vehicle1 = new Vehicle1('Toyota Corolla', 2009);console.log(vehicle1.make); // Toyota Corollavehicle1.make = 'Ford Mustang';console.log(vehicle1.toString()) // Toyota Corolla 2009
We define a Vehicle class with two read-only attributes and a custom toString method. Let's do the same thing in ES6:
class Vehicle {    constructor(make, year) {        this._make = make;        this._year = year;    }    get make() {        return this._make;    }    get year() {        return this._year;    }    toString() {        return `${this.make} ${this.year}`;    }}var vehicle = new Vehicle('Toyota Corolla', 2009);console.log(vehicle.make); // Toyota Corollavehicle.make = 'Ford Mustang';console.log(vehicle.toString()) // Toyota Corolla 2009
The classes defined in the above two examples are different. To enjoy the benefits of the new get syntax, we just define make and year as common attributes. This allows them to be changed externally. If you need a strict private property, continue using defineProperty.
2. Class Declaration
A class declaration is a way to define a class. As shown below, a class can be defined by using the class keyword followed by a class Name (Polygon here.
class Polygon {    constructor(height, width) {        this.height = height;        this.width = width;    }}
3. Variable escalation
The difference between the class declaration and the function declaration is that the function declaration promotes variables, but the class declaration does not.
That is to say, You must declare the class before using it. Otherwise, the code will throw a ReferenceError exception, as shown below:
var p = new Polygon(); // ReferenceErrorclass Polygon {}
4. Class expression
A class expression is another way to define a class. In a class expression, the class name is dispensable. If a class name is defined, the class name can be accessed only within the class body.
Anonymous
var Polygon1 = class {    constructor(height, width) {        this.height = height;        this.width = width;    }};
Named
var Polygon2 = class Polygon {    constructor(height, width) {        this.height = height;        this.width = width;    }};
Note: The class expression and class declaration will not be upgraded.
5. Prototype Method
class Polygon3 {    constructor(height, width) {        this.height = height;        this.width = width;    }    get area() {        return this.calcArea()    }    calcArea() {        return this.height * this.width;    }}const square = new Polygon3(10, 10);console.log(square.area);// 100
6. Static Method
The static keyword is used to define the static method of the class. Static methods are those that do not need to instantiate the class and can be directly accessed using the class name. Note that static methods cannot be called by instantiated objects. Static methods are often used as tool functions.
class Point {    constructor(x, y) {        this.x = x;        this.y = y;    }    static distance(a, b) {        const dx = a.x - b.x;        const dy = a.y - b.y;        return Math.sqrt(dx*dx + dy*dy);    }}const p1 = new Point(5, 5);const p2 = new Point(10, 10);console.log(Point.distance(p1, p2));
7. class inheritance
Create a subclass using extends
The extends keyword can be used in a class declaration or expression to create a subclass that inherits a class.
Class Animal {constructor (name) {this. name = name;} speak () {console. log (this. name + 'makes a noise. ') ;}} class Dog extends Animal {speak () {console. log (this. name + 'barks. ') ;}} var d = new Dog ('mitzie'); d. speak (); // 'mitzie barks. '// It can also be used for the original prototype inherited "class": function animal (name) {this. name = name;} Animal2.prototype. speak = function () {console. log (this. name + 'makes a noise. ');} class Dog2 e Xtends animal {speak () {super. speak (); console. log (this. name + 'barks. ') ;}} var d2 = new Dog2 ('mitzie'); d2.speak (); // note that classes cannot inherit General (non-constructed) objects. If you want to create a class to inherit a common Object, you need to use the Object. setPrototypeOf (): var anim_3 = {speak () {console. log (this. name + 'makes a noise. ') ;}}; class Dog3 {constructor (name) {this. name = name;} speak () {super. speak (); console. log (this. name + 'barks. ') ;}} Object. setPrototypeOf (Dog3.prototype, anim_3); var d3 = new Dog3 ('mitzie'); d3.speak ();
8. Species
You may want the Array class MyArray to return an Array object. This species mode allows you to override the default constructor.
For example, if you use a method like map () to return the default constructor, you want this method to return the parent-level Array object instead of the MyArray object. Symbol. species can be implemented as follows:
class MyArray extends Array {    // Overwrite species to the parent Array constructor    static get [Symbol.species]() { return Array; }}var a = new MyArray(1,2,3);var mapped = a.map(x => x * x);console.log(mapped instanceof MyArray); // falseconsole.log(mapped instanceof Array);   // true
9. The super keyword can be used to call the constructor or class method of its parent class.
Class Cat {constructor (name) {this. name = name;} speak () {console. log (this. name + 'makes a noise. ') ;}} class Lion extends Cat {speak () {super. speak (); console. log (this. name + 'roars. ') ;}} new Lion ('Nick '). speak (); // Let's look at the important example class Animal4 {constructor () {this. type = 'animal ';} says (say) {console. log (this. type + 'says '+ say) ;}} let animal4 = new Animal4 (); animal4.says ('hello') // animal says helloclass Cat4 extends Animal4 {constructor () {super (); this. type = 'cat'; // 1. subclass definition constructor; // 2. call super (); // 3. this will point to the subclass instance cat4. Otherwise, this in the constructor reports an error or this in the subclass method points to the parent class instance} let cat4 = new Cat4 (); cat4.says ('hello '); // cat says hello

The code above first defines a "class" with class. We can see that there is a constructor method in it. this is the constructor method, and this keyword indicates the instance object.
In short, the methods and attributes defined in constructor are the instance objects, while the methods and attributes defined outside constructor are shared by all instance objects.
Classes can be inherited by using the extends keyword, which is much clearer and more convenient than es5.
The Cat class is defined above. This class inherits all attributes and methods of the Animal class through the extends keyword.
Super keyword, which refers to the instance of the parent class (that is, the this object of the parent class ). The subclass must call the super method in the constructor method. Otherwise, an error is returned when the instance is created.
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.
The Inheritance Mechanism of ES6 is to first create the Instance Object of the parent class this (so the super method must be called first), and then modify this with the constructor of the subclass.

End of es6

Related Article

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.