類
class Star {
// constructor 函數,可以接受傳遞過來的參數,同時返回實例對象
// constructor 函數,只要 new 生成實例時,就會自動調用這個函數,如果不寫類也會自動生成
constructor(uname) {
this.uname = uname;
}
// 創建方法
print(content) {
return content + this.uname;
}
};
var zs = new Star('zs');
zs.print('hello world'); // 調用
類 constructor
構造函數
constructor()
是類的構造函數(默認方法),用於傳遞參數,返回實例對象;通過new命令生成對象實例時,自動調用該方法,如果沒有顯示定義,類內部會自動創建一個 constructor()
繼承
class Father {
constructor(x, y) {
this.x = x;
this.y = y;
}
sum() {
console.log(this.x + this.y);
// console.log(1 + 2);
}
}
class Son extends Father {
// 子類中沒有 constructor 構造方法時,並且父類中的方法沒有涉及到父類中的 constructor 子類是可以直接通過 extends 來繼承父類身上的方法的
constructor(uname) {
// 如果運用到了父類中的構造函數 constructor 子類想再次調用則需要 子類也聲明 constructor 構造函數並且通過 super() 方法傳遞想要的參數,進行計算
super(11, 22); // super() 方法必須寫到子類構造方法中的最前面,高於自身的this
this.uname = uname;
}
// 如果子類中存在於父類相同的方法,調用時就近原則
sum() {
console.log(2 + 2);
// 也可以通過super()方法直接調用 父類中的sum方法
super.sum();
}
// 子類可以拓展自己的方法
print() {
console.log(this.uname);
}
}
var son = new Son();
1. son.sum(); // 3
2. son.sum(); // 33
3. son.sum(); // 4 33