ES6 classes provide a compact way to create objects and express inheritance in JavaScript. The syntax is an abstraction over prototypes, not a replacement for them. section 7.4 section 7.4.1
Class syntax supports several common patterns:
- Use a constructor to initialize instance properties; define methods in the class body for instances to share. section 7.4.1
- Use static methods for class-level behavior that is not available on instances. section 7.4.1
- Use extends to express inheritance and super to call the base class constructor. section 7.4.2
Listing 7.13. Creating a class in ES6
class Ninja{ #A
constructor(name){ #B
this.name = name; #B
} #B
swingSword(){ #C
return true; #C
} #C
}
var ninja = new Ninja("Yoshi"); #D
assert(ninja instanceof Ninja, "Our ninja is a Ninja"); #E
assert(ninja.name === "Yoshi", "named Yoshi"); #E
assert(ninja.swingSword(), "and he can swing a sword"); #E
A Ninja example shows a constructor, a shared method, instance creation, and checks of the resulting instance. section 7.4.1
Listing 7.15. Inheritance in ES6
class Person {
constructor(name){
this.name = name;
}
dance(){
return true;
}
}
class Ninja extends Person { #A
constructor(name, weapon){
super(name); #B
this.weapon = weapon;
}
wieldWeapon(){
return true;
}
}
var person = new Person("Bob");
assert(person instanceof Person, "A person's a person");
assert(person.dance(), "A person can dance.");
assert(person.name === "Bob", "We can call it by name.");
assert(!(person instanceof Ninja), "But it's not a Ninja");
assert(!("wieldWeapon" in person), "And it cannot wield a weapon");
var ninja = new Ninja("Yoshi", "Wakizashi");
assert(ninja instanceof Ninja, "A ninja's a ninja");
assert(ninja.wieldWeapon(), "That can wield a weapon");
assert(ninja instanceof Person, "But it's also a person");
assert(ninja.name === "Yoshi" , "That has a name");
assert(ninja.dance(), "And enjoys dancing");
A Person and Ninja example demonstrates extends, super, and inherited behavior. section 7.4.2




















