Under the hood, ES6 classes are not something that is radically new: They mainly provide more convenient syntax to create old-school constructor functions.
- Axel Rauschmayer
var Dog = function(name){
this.name = name;
}
Dog.prototype.call = function(){
return "Come here " + this.name;
}
Dog.prototype.bark = function(){
return "Bow wow";
}
// ES5 way
var myDog = new Dog('Twiggy');
myDog.bark() // 'Bow wow'class Dog {
constructor(name){
this.name = name;
}
call(){
return "Come here " + this.name;
}
bark(){
return "Bow wow"
}
}
// ES6 way
var myDog = new Dog('Twiggy');
myDog.bark() // 'Bow wow'class Dog {
public Dog(String name){
this.name = name;
}
public static String call(){
return 'Come here ' + this.name;
}
public static String bark(){
return 'Bow wow';
}
}
// Java// Class expression
class Food {}
// Class declaration
var Food = {}
// OR
var Food = goodFood{}
class Dog extends Animal {
// class body
}class Car{
constructor(make, model){
this.make = make;
this.model = model;
}
}
var ford = Car('Ford', 'Elantra'); // undefinedclass Car{
constructor(make, model){
if(!new.target) return new Car(make, model);
this.make = make;
this.model = model;
}
}
var ford = Car('Ford', 'Elantra'); // we good!Methods on the constructor function itself, which are not available on instances of the class.
Any method that isn't a constructor or a static method
The name comes from the fact that we used to achieve this functionality by attaching functions to the .prototype of functions-as-constructors