Class
Define a Class
A class may have only one constructor
class Car{
constructor(maker)
{
this.maker = maker;
}
getMaker()
{
return this.maker;
}
setMaker(m)
{
this.maker = m;
}
}
<script src="car.js"></script>
<script type="text/javascript">
const car = new Car("Honda");
console.log(car.getMaker())
car.setMaker("Toyota");
console.log(car.getMaker());
</script>
// instanceof
class Person
{
constructor(n)
{
this.name = n;
}
}
var p = new Person();
console.log(p instanceof Person); //true
Keyword Arguments in Constructor
class Car{
constructor({maker = 'Honda', year = 2016})
{
this.maker = maker;
this.year = year;
}
getMaker()
{
return this.maker;
}
getYear()
{
return this.Year;
}
setMaker(m)
{
this.maker = m;
}
setYear(y)
{
this.year = y;
}
}
<script src="car.js"></script>
<script type="text/javascript">
const c0 = new Car('Honda', 2016); // const c0 = new Car({maker: 'Honda', year: 2016});
const c1 = new Car("Honda"); // const c1 = new Car({maker: "Honda"});
const c2 = new Car(2016); // const c2 = new Car({year: 2016});
console.log(c0);
console.log(c1);
console.log(c2);
</script>
Static Method
class Car{
constructor(maker)
{
this.maker = maker;
}
static info()
{
console.log('Hello World!');
}
}
<script src="car.js"></script>
<script type="text/javascript">
const car = new Car("Honda");
Car.info();
</script>
Inheritance
class Vehicle
{
constructor(maker)
{
this.maker = maker;
}
getMaker() {return this.maker;}
setMaker(m) {this.maker = m;}
}
class Car extends Vehicle{
constructor(maker, year)
{
super(maker);
this.year = year;
}
getYear() {return this.year;}
setYear(y) {this.year = y;}
}
<script type="text/javascript">
const v = new Vehicle("Honda");
const c = new Car("Honda", 2016);
console.log(v.getMaker());
console.log(c.getMaker(), c.getYear());
</script>
Method Overriding
class Vehicle
{
constructor(maker)
{
this.maker = maker;
}
print() {console.log(this.maker);}
getMaker() {return this.maker;}
setMaker(m) {this.maker = m;}
}
class Car extends Vehicle{
constructor(maker, year)
{
super(maker);
this.year = year;
}
print() {console.log(this.maker+' '+this.year);}
getYear() {return this.year;}
setYear(y) {this.year = y;}
}
var v = new Vehicle('Honda');
v.print();
var c = new Car('Honda', 2016);
c.print();
Getter and Setter
class Car{
constructor(maker)
{
this.maker = maker;
}
get carmaker() // the function name should not be same as the attribute name to avoid the recursively call
{
return this.maker;
}
set carmaker(m)
{
this.maker = m;
}
}
<script src="car.js"></script>
<script type="text/javascript">
const car = new Car("Honda");
console.log(car.carmaker);
car.carmaker = "Toyota";
console.log(car.carmaker);
</script>