ES6 Classes formalize the common JavaScript pattern of simulating class-like inheritance hierarchies
using functions and prototypes. They are effectively simple sugaring over prototype-based OO, offering
a convenient declarative form for class patterns which encourage interoperability.
Classes (as shipped in Chrome) support prototype-based inheritance, constructors, super calls, instance
and static methods. The samples included in this demo are:
Creating a new class (declaration-form)
Creating a new class (expression-form)
Extending an existing class
Subclassing methods of a parent class
Defining static methods
Subclassing built-ins
Live Output
JavaScript Snippet
'use strict';// Example 1: Creating a new class (declaration-form)// ===============================================================// A base class is defined using the new reserved 'class' keywordclassPolygon{// ..and an (optional) custom class constructor. If one is// not supplied, a default constructor is used instead:// constructor() { }constructor(height,width){this.name='Polygon';this.height=height;this.width=width;}// Simple class instance methods using short-hand method// declarationsayName(){ChromeSamples.log('Hi, I am a ',this.name+'.');}sayHistory(){ChromeSamples.log('"Polygon" is derived from the Greek polus (many) '+'and gonia (angle).');}// We will look at static and subclassed methods shortly}// Classes are used just like ES5 constructor functions:letp=newPolygon(300,400);p.sayName();ChromeSamples.log('The width of this polygon is '+p.width);// Example 2: Creating a new class (expression-form)// ===============================================================// Our Polygon class above is an example of a Class declaration.// ES6 classes also support Class expressions - just another way// of defining a new class. For example:constMyPoly=classPoly{getPolyName(){ChromeSamples.log('Hi. I was created with a Class expression. My name is '+Poly.name);}};letinst=newMyPoly();inst.getPolyName();// Example 3: Extending an existing class// ===============================================================// Classes support extending other classes, but can also extend// other objects. Whatever you extend must be a constructor.//// Let's extend the Polygon class to create a new derived class// called Square.classSquareextendsPolygon{constructor(length){// The reserved 'super' keyword is for making super-constructor// calls and allows access to parent methods.//// Here, it will call the parent class' constructor with lengths// provided for the Polygon's width and heightsuper(length,length);// Note: In derived classes, super() must be called before you// can use 'this'. Leaving this out will cause a reference error.this.name='Square';}// Getter/setter methods are supported in classes,// similar to their ES5 equivalentsgetarea(){returnthis.height*this.width;}setarea(value){this.area=value;}}lets=newSquare(5);s.sayName();ChromeSamples.log('The area of this square is '+s.area);// Example 4: Subclassing methods of a parent class// ===============================================================classRectangleextendsPolygon{constructor(height,width){super(height,width);this.name='Rectangle';}// Here, sayName() is a subclassed method which// overrides their superclass method of the same name.sayName(){ChromeSamples.log('Sup! My name is ',this.name+'.');super.sayHistory();}}letr=newRectangle(50,60);r.sayName();// Example 5: Defining static methods// ===============================================================// Classes support static members which can be accessed without an// instance being present.classTriple{// Using the 'static' keyword creates a method which is associated// with a class, but not with an instance of the class.statictriple(n){n=n||1;returnn*3;}}// super.prop in this example is used for accessing super-properties from// a parent class. This works fine in static methods too:classBiggerTripleextendsTriple{statictriple(n){returnsuper.triple(n)*super.triple(n);}}ChromeSamples.log(Triple.triple());ChromeSamples.log(Triple.triple(6));ChromeSamples.log(BiggerTriple.triple(3));// var tp = new Triple();// ChromeSamples.log(tp.triple()); tp.triple is not a function// Example 6: Subclassing built-in classes and DOM// ===============================================================// Extend Date built-inclassMyDateextendsDate{constructor(){super();}getFormattedDate(){varmonths=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];returnthis.getDate()+'-'+months[this.getMonth()]+'-'+this.getFullYear();}}varaDate=newMyDate();ChromeSamples.log(aDate.getTime());ChromeSamples.log(aDate.getFormattedDate());// Extend Uint8ArrayclassExtendedUint8ArrayextendsUint8Array{constructor(){super(10);this[0]=255;this[1]=0xFFA;}}vareua=newExtendedUint8Array();ChromeSamples.log(eua.byteLength);// Extend DOM Audio elementclassMyAudioextendsAudio{constructor(){super();this._lyrics='';}getlyrics(){returnthis._lyrics;}setlyrics(str){this._lyrics=str;}}varplayer=newMyAudio();player.controls=true;player.lyrics='Never gonna give you up';document.querySelector('body').appendChild(player);ChromeSamples.log(player.lyrics);// Note: The V8 in Chrome 42 supports subclassing built-ins but Arrays.// Subclassing arrays supported in Chrome 43.classStackextendsArray{constructor(){super();}top(){returnthis[this.length-1];}}varstack=newStack();stack.push('world');stack.push('hello');ChromeSamples.log(stack.top());ChromeSamples.log(stack.length);
You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.