There are two ways that a class can be define.
- using class declaration.
- using class expression.
using class declaration.
The class declaration doesn't allow an existing class to be declared again and will throw a type error if attempted.
class vehicle{ constructor(name, manufacturer) { this.name = name; this.manufacturer = manufacturer; } }
using class expression.
There are two ways to define class using class declaration. with name or without name.
with name.
if named, the name of the class is local to the class body only.
var MyClass = class vehicle { constructor(name, manufacturer) { this.name = name; this.manufacturer = manufacturer; } };
without name.
var MyClass = class { constructor(name, manufacturer) { this.name = name; this.manufacturer = manufacturer; } };if you try to access before declaring the class it will throw Reference Error.
What is constructor.
The constructor method is a specialmethod for creating and initializing an object created with a class.There can have only one constructor per class.
Add method to a class.
class vehicle { constructor(name, manufacturer) { this.name = name; this.manufacturer = manufacturer; } PrintName() { return this.name; } static PrintManufacturer(manufact) { this.manufacturer=manufact; return this.manufacturer; } }; const jeep=new vehicle("defender","LandRover"); console.log(jeep.PrintName()); console.log(vehicle.PrintManufacturer("Toyota"));
To access a static function inside an class don't need a instance.can access directly with class name.static methods cannot be called through class instance.
sub classes.
class vehicle { constructor(name, manufacturer) { this.name = name; this.manufacturer = manufacturer; } PrintName() { return this.name; } static PrintManufacturer(manufact) { this.manufacturer=manufact; return this.manufacturer; } }; class car extends vehicle{ PrintName(){ return this.name+" is in car sub class"; } }; var car1=new car("Mustang","Ford"); console.log(car1.PrintName());
No comments:
Post a Comment