一、類的基本定義和生成實例
{
// 基本定義和生成實例
class Parent {
constructor(name = 'parent') {
this.name = name;
}
}
// 創(chuàng)建類的實例
let v_parent = new Parent('v');
console.log('構造函數(shù)和實例', v_parent);
}
二、繼承
{
// 繼承 通過extends關鍵字
class Parent {
constructor(name = 'parent') {
this.name = name;
}
}
class Child extends Parent {
}
console.log('繼承', new Child());
}
三、繼承傳遞參數(shù)
在子類中利用super(),將參數(shù)傳遞進去可覆蓋父類中的值
{
// 繼承傳遞參數(shù)
class Parent {
constructor(name = 'parent') {
this.name = name;
}
}
class Child extends Parent {
constructor(name = 'child') {
//將子類的name傳遞進去,覆蓋父類中的name
// 注意:super要放在第一行
super(name);
this.type = 'child type'
}
}
console.log('繼承傳遞參數(shù)', new Child());
}
四、類的getter setter方法
{
// getter setter
class Parent {
constructor(name = 'parent') {
this.name = name;
}
get longName() {
return 'mk' + this.name;
}
set longName(value) {
this.name = value;
}
}
let v = new Parent();
console.log('getter', v.longName);
v.longName = 'hello';
console.log('setter', v.longName);
}
五、靜態(tài)方法 static
靜態(tài)方法:通過static修飾的方法
{
// 靜態(tài)方法 static
class Parent {
constructor(name = 'parent') {
this.name = name;
}
static tell() {
console.log('tell');
}
}
// 靜態(tài)方法 只能通過類調用,不能通過類的實例去調用
Parent.tell();
//以下這種寫法不正確
// let v=new Parent();
// v.tell();
}
六、靜態(tài)屬性
{
// 靜態(tài)屬性
class Parent {
constructor(name = 'parent') {
this.name = name;
}
static tell() {
console.log('tell');
}
}
//直接在類上定義,通過這種方式實現(xiàn)靜態(tài)屬性
Parent.type = 'test';
//讀取時,直接調用Parent.type
console.log('靜態(tài)屬性', Parent.type);
}