New features of JavaScript ES6 define Class_javascript techniques with new methods

Source: Internet
Author: User
Tags class definition inheritance

ES6 (ECMAScript 6) is the upcoming new version of the JavaScript language standard, code-named Harmony (meaning of harmony, obviously did not keep pace with our country, we have entered the Chinese Dream version). The last standard was enacted in 2009 ES5. The ES6 is currently in the process of standardization and is expected to release the officially finalized version in December 14. But most of the standards are in place, and browser support for ES6 is also being implemented.

The way in which classes are defined in ES6 is the syntactic sugars of the classes defined in ES3 and ES5. Although there are some differences, but the overall definition of the way of the class is more concise, class inheritance more convenient, if you want to ES6 in the inheritance more familiar with the best understanding of the ES5, the way to inherit, blog Park said JS inherited a lot of articles, Want to know more about the students themselves to search;

Define a class:

Every class defined by using class method defaults to a constructor function, which is the main function of the constructor, which points to the generated instance, say () {} as the method on the prototype, and we define a simple class:

Run the following code

"Use strict";
Class Person {
 Constructor (name) {
  this.name = name;
 }
 Say () {
  console.log ("Say hi");
 }
;
New person (). Say (); The console will output say hi

Note: The class declared in ES6 does not have a problem with the function declaration ahead of time. Class must be declared before use, otherwise there will be an exception, we just put the above demo code location, immediately error, (if the thinking in ES5 to understand the words, the declaration of the class did not declare advance, the declaration of advance knowledge points, The class declared by class class name {} is the var class name = function () {});

Run the following code

 "Use strict";
New person (). Say ();
Class Person {
 Constructor (name) {
  this.name = name;
 }
 Say () {
  console.log ("Say hi");
 }
;

To define a static method for a function:

If you define a function, inside the curly braces, the function name is declared static, then the function is a quiescent function, static method, and the prototype does not matter:

Run the following code

 "Use strict";
Class Person {
 Constructor (name) {
  this.name = name;
 }
 Static say () {
  console.log ("Say hi");
 }
;
Person.say ();

 To define a prototype method:

To define a prototype method, declare this directly: function name () {}, the parentheses inside the argument list, curly braces inside the code block, ES5 to define the prototype method is through: constructors. Prototype. Prototype method name () {}, which is a tedious form of writing, a bit of a way to use ES6 to define a prototype Like Java and C #, these are features of a higher-level language:

Run the following code

 "Use strict";
Class Person {
 Constructor (name) {
  this.name = name;
 }
 Say () {
  console.log ("Say hi");
 }
 Sing () {
  console.log ("Lalalalala");
 }
;
New person (). Say (); Output: Say hi
new person (). sing ();//output: Lalalalala

  Static properties and Stereotype properties:

Static properties can only be defined after the class definition is complete, a little pit dad, language authors can implement this method to avoid code confusion, all static properties in the same place defined, code back more standardized?

Run the following code

 "Use strict";
Class Person {
 Constructor (name) {
  this.name = name;
 }
};
Person.hands = 2;
Console.log (Person.hands);

The prototype can not define attributes, we can only define set and get on the prototype, value and set value device, we should pay attention to the value of the device and set the value of 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: Heheda
console.log (p._name);//output: Heheda

If you want to define a prototype attribute, define the attribute directly within the constructor, and if it is inherited, the subclass inherits this property of the parent class as well:

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 has inherited, but this kind of inheritance often around, ES6 inheritance is only based on the prototype inherited encapsulation (grammatical sugar), although indeed concise a lot, or Java inheritance more studious Ah, the following demo example of the Sman is Superman's meaning, don't think crooked;

Run the following code

 "Use strict";
Class Person {
 Constructor (name) {
  this.name = name;
 }
 Say () {
  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 say hi Clark

If you want to use inheritance, you must perform a super () call to the parent class in the subclass. The no person compiler throws the error, the super in the subclass has three kinds of functions, the first is to call as the constructor directly, the second is as the parent class instance, the third is to call the static method of the parent class in the static method in the subclass;

ES6 inherited and ES5 inheritance of the main difference, the common inheritance in ES5 is the prototype of the handle class set to 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 (); Inheriting prototypes;
Sub.prototype.constructor = Sub; Correction of constructor;

The inheritance that is implemented in ES6 is more sophisticated and does not interfere with the parent class, which combines the 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 this property and method;
sub.__proto__ = Sup; Inherit sup static properties;
Sub.prototype = Object.create (Sup.prototype, {constructor: {value:sub, Enumerable:false, Writable:true, configurable : true}}); Inherit the prototype property and overwrite the constructor;

Pictures can be more easily see the difference between the two, illustrated ES5 and ES6 inheritance of the difference: http://keenwon.com/1524.html;

 ES5 Simulate ES6 Inheritance:

Because of the transcoding device Babel, we can through the ES5 code, to spy ES6 inheritance in the end is how to achieve, ES6 inheritance:

Run the following code

"Use strict";
Class Person {
 Constructor (name) {
  this.name = name;
 }
 Say () {
  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 ES5, the code became like this, and I added a little note to forgive my bohemian love for 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 prototype if (Protoprops) Defineproperties (constructor
   . prototype, Protoprops);
   Copy attribute 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 Initi
  Alised-super () hasn ' t been called '); return call && [typeof call = =]Object "| | typeof call = = = "function")?
 call:self; //Below is the ES6 inheritance using the ES5 expression code, _inherits the inheritance of the prototype and the inheritance of the parent Class State property: Function _inherits (subclass, superclass) {if (typeof Superclas S!== "function" && superclass!== null) {throw new TypeError ("Super expression must either be null or a funct
  Ion, not "+ typeof superclass);
  //Inherits the prototype of the parent class and corrects the constructor as a subclass; Subclass.prototype = object.create (Superclass && Superclass.prototype, {constructor: {value:subclass,
  Enumerable:false, Writable:true, Configurable:true}}); It also defines __proto__ as the parent class for the subclass, which enables static property inheritance; if (superclass) object.setprototypeof?
  Object.setprototypeof (subclass, superclass): subclass.__proto__ = superclass;
 Finally if the developer: new subclass, the actual state is: Object {__proto__: Parent class, Constuctor: Subclass}};
 /* var Sup = function () {};
 var Sub = function () {};
 _inherits (Sub, Sup); The meaning of this inheritance realization; Inherits the parent class as a subclass of an object, and as a constructor, the subclass inherits sub.prototype.__proto__ = = Sup.prototype//true Sub.prototype.constructor = = Sub;//true Su b.__proto__ = =Sup;//true */var person = function () {function person (name) {_classcallcheck (this, person);
  THIS.name = name;
    _createclass (person, [{key: "Say", value:function say () {console.log ("Say hi");
   return this;
  }
  }]);
 return person;
 }();
 ;
  var Sman = function (_person) {_inherits (Sman, _person);
   function Sman (name, power) {//The this.__proto__ already points to the Prototyp of the constructor _classcallcheck (this, sman);
   This sentence is equivalent to the super () in the ES6, the attribute of the parent class through call, the implementation of inheritance;
   var _this = _possibleconstructorreturn (This, object.getprototypeof (Sman). "Call" (this, name);
   _this.superpower = power;
   Dynamic return to _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 implement multiple inheritance, written by: Class Sub extends Mix (obj0, obj1, Obj2), mix is just a method, this method we have to define ourselves:

Run the following code

  

The above is a small set to introduce the new features of JavaScript ES6 use the new method to define the knowledge of class, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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.