ECMAScript 2015, also known as ES6, introduced JavaScript Classes. JavaScript Classes are templates for JavaScript Objects. JavaScript Class SyntaxUse the keyword class to create a class. Always add a method named constructor(): Syntax class ClassName { Example class Car { The example above creates a class named "Car". The class has two initial properties: "name" and "year". A JavaScript class is not an object. It is a template for JavaScript objects. Using a ClassWhen you have a class, you can use the class to create objects: Example let myCar1 = new Car("Ford", 2014); Try it Yourself » The example above uses the Car class to create two Car objects. The constructor method is called automatically when a new object is created. The Constructor MethodThe constructor method is a special method:
If you do not define a constructor method, JavaScript will add an empty constructor method. Class MethodsClass methods are created with the same syntax as object methods. Use the keyword class to create a class. Always add a constructor() method. Then add any number of methods. Syntax class ClassName { Create a Class method named "age", that returns the Car age: Example class Car { let myCar = new
Car("Ford", 2014); Try it Yourself » You can send parameters to Class methods: Example class Car { let date = new Date(); let myCar = new Car("Ford", 2014); Try it Yourself » Browser SupportThe following table defines the first browser version with full support for Classes in JavaScript:
You will learn a lot more about JavaScript Classes later in this tutorial. |