ES6 (ECMAScript 6) is the standard for the upcoming new version of JavaScript language, codenamed harmony (the meaning of harmony is obviously not keeping up with my country's pace, we have entered the Chinese Dream version). The last standard was formulated as ES5, which was issued in 2009. Currently, the standardization of ES6 is in progress, and the officially finalized version is expected to be released in December 2014. But most standards are ready, and support for ES6 by browsers is also being implemented.
The way to define classes in ES6 is the syntax sugar for defining classes in ES3 and ES5. Although there are some differences, the overall way to define classes is more concise and class inheritance is more convenient. If you want to be more familiar with inheritance in ES6, it is best to understand the method of prototype inheritance in ES5. There are many articles in the blog park that say JS inheritance. Students who want to have an in-depth understanding will search it themselves;
Define a class:
Each class defined using the class method has a constructor function by default. This function is the main function of the constructor function. This inside the function body points to the generated instance. Say() {} is the method on the prototype. We define a simple class:
Run the following code
"use strict";class Person { constructor(name) { this.name = name; } says () { console.log("say hi"); }};new Person().say(); //The console will output say hiNote: The class declared in ES6 does not have the problem of function declaration in advance. The class must be declared first and then used, otherwise an exception will occur. We just change the code position in the above demo and report an error immediately. (If you understand it with the thinking in ES5, the declared class does not declare in advance. For knowledge points about the declaration in advance, the class declared through the class name {} is the var class name = function(){});
Run the following code
"use strict";new Person().say();class Person { constructor(name) { this.name = name; } says () { console.log("say hi"); }};Static methods to define functions:
If static is declared in the braces before the function name when defining a function, then this function is a static function, a static method, and has nothing to do with the prototype:
Run the following code
"use strict";class Person { constructor(name) { this.name = name; } static says () { console.log("say hi"); }};Person.say();Define the prototype method:
Define the prototype method and declare it directly like this: Function name() {}, the brackets are parameter list, and the braces are code blocks. The method to define the prototype in ES5 is to use: constructor.prototype. Prototype method name() {}. This writing form is very cumbersome. The way to define the prototype using ES6 is a bit like java and C#. These are the characteristics of relatively high-level languages:
Run the following code
"use strict";class Person { constructor(name) { this.name = name; } says () { console.log("say hi"); } sing () { console.log("lalalala"); }};new Person().say(); //Output: say hinev Person().sing(); //Output: lalalalalaStatic properties and prototype properties:
It is a bit tricky to define static properties after the class definition is completed. The language author implements this method to avoid code confusion. All static properties are defined in the same place, so how can the code be more standardized?
Run the following code
"use strict";class Person { constructor(name) { this.name = name; }};Person.hands = 2;console.log(Person.hands);Attributes cannot be defined on the prototype. We can only define set and get on the prototype, value and setter. Note that the value and setter are on the prototype...:
Run the following code
class Person { constructor(_name) { this._name = _name; } get name() { return this._name; } set name(_name) { this._name = _name; }}var p = new Person();p.name = "heheda";console.log(p.name); //Output: hehedaconsole.log(p._name); //Output: hehedaIf you want to define a prototype attribute, just define the attribute inside the constructor. If it is inherited, the subclass will also inherit the attribute of the parent class:
Run the following code
class Person { constructor() { this.name = "default"; }}class Man extends Person{ constructor() { super(); }}console.log( new Man().name );Inheritance extends of the class:
ES5 already has inheritance, but this kind of inheritance often circulates. ES6 inheritance is only based on prototype inheritance encapsulation (synonym sugar). Although it is indeed much simpler, Java inheritance is easier to learn. SMan in the following Demo example means superman, don't think so;
Run the following code
"use strict";class Person { constructor(name) { this.name = name; } says () { console.log("say hi"); return this; }};class SMan extends Person { constructor (name, power) { super(name); this.superPower = power; } show () { console.log(this.superPower); return this; }}console.log( new SMan("Clark", "pee").show().say().name ); //Output: pee says hi ClarkIf you want to use inheritance, super() must be executed in the subclass to call the parent class. Otherwise, the compiler will throw an error. Super in the subclass has three functions. The first is to call it directly as a constructor, the second is to act as an instance of the parent class, and the third is to call the static method of the parent class in the static method in the subclass;
The main difference between ES6 inheritance and ES5 inheritance. The commonly used inheritance in ES5 is to set the prototype of the subclass as an instance of the parent class. The subclass naturally has all the methods and properties of the parent class:
Run the following code
var Sup = function() { this.sub = true;};Sup.prototype.protoSup = {sup:"sup"};var Sub = function() { this.sub = true;};Sub.prototype = new Sup(); //Inherit the prototype; Sub.prototype.constructor = Sub; //Fix constructor;The inheritance implemented in ES6 is more exquisite and will not be disturbed by the parent class. This inheritance is a combination of apply inheritance and prototype inheritance implementation:
Run the following code
var Sup = function() { this.sub = true;};var Sub = function() { this.sup = true; Sup.apply(this); //Inherit the properties and methods of this;};Sub.__proto__ = Sup; //Inherit the static properties of Sup; Sub.prototype = Object.create( Sup.prototype, {constructor : { value: Sub, enumerable: false, writable: true, configurable: true }}); //Inherit the prototype attributes and overwrite the constructor;It is easier to see the difference between the two with pictures, and the picture shows the difference between inheritance between ES5 and ES6: http://keenwon.com/1524.html;
ES5 simulates the inheritance of ES6:
Because of the transcoder babel, we can use ES5 code to explore how ES6 inheritance is implemented, and ES6 inheritance:
Run the following code
"use strict";class Person { constructor(name) { this.name = name; } says () { console.log("say hi"); return this; }};class SMan extends Person { constructor (name, power) { super(name); this.superPower = power; } show () { console.log(this.superPower); return this; }}console.log( new SMan("Clark", "pee").show().say().name );After using babel to convert it to ES5, the code became like this. I added a little comment myself, forgive me for being unruly and loving freedom...:
Run the following code
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { //Copy the prototype if (protoProps) defineProperties(Constructor.prototype, protoProps); //Copy the property if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } //The following is the code expressed in ES6 inherits. _inherits implements the inheritance of the prototype and the inheritance of the parent class state attributes: function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } //Inherit the prototype of the parent class and correct the constructor as a subclass; subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); //Define __proto__ for the subclass object, so that static attribute inheritance can be achieved; if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; //The last if the developer: new subclass, the actual state is: Object {__proto__:parent class, constructor:subclass} }; /* var Sup = function() {}; var Sub = function() {}; _inherits(Sub, Sup); //The meaning of this inheritance implementation; As a subclass of the object inherits the parent class, as a constructor, the subclass inherits Sub.prototype.__proto__ === Sup.prototype //true Sub.prototype.constructor === Sub;//true Sub.__proto__ === Sup;//true */ var Person = function () { function Person(name) { _classCallCheck(this, Person); this.name = name; } _createClass(Person, [{ key: "say", value: function says() { console.log("say hi"); return this; } }]); return Person; }(); ; var SMan = function (_Person) { _inherits(SMan, _Person); function SMan(name, power) { //At this time this.__proto__ has pointed to the constructor's prototype _classCallCheck(this, SMan); //This sentence is equivalent to super() in ES6, passing the parent class's attributes through the call, and executing inheritance; var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(SMan).call(this, name)); _this.superPower = power; //Dynamic return _this; return _this; } _createClass(SMan, [{ key: "show", value: function show() { console.log(this.superPower); return this; } }]); return SMan; }(Person); console.log(new SMan("Clark", "pee").show().say().name);Multiple inheritance:
Use mix-in to achieve multiple inheritance, and the writing method is: class Sub extends mix(obj0, obj1, obj2) . mix is just a method, we need to define this method ourselves:
Run the following code
<html><head> <meta charset="utf-8"></head><body><script> "use strict"; function mix(...mixins) { class Mix {} for (let mixin of mixins) { copyProperties(Mix, mixin); copyProperties(Mix.prototype, mixin.prototype); } return Mix; } function copyProperties(target, source) { for (let key of Reflect.ownKeys(source)) { if ( key !== "constructor" && key !== "prototype" && key !== "name" ) { let desc = Object.getOwnPropertyDescriptor(source, key); Object.defineProperty(target, key, desc); } } } class Man{ work () { console.log("working"); } } class Woman{ say () { console.log("saying"); } } class SuperMan extends mix(Man, Woman) { constructor () { super(); } } var sm = new SuperMan(); sm.work(); sm.say(); //In fact, they do not have an inheritance relationship, they just copy the attributes to the subclass; console.log(sm instanceof Man); console.log(sm instanceof Woman);</script></body></html>The above is the relevant knowledge about the new features of JavaScript ES6 that the editor introduced to you. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support to Wulin.com website!