一、Class 繼承
用 class定義對象
的另一個巨大的好處是繼承更方便了。
/*
* class 的定義包含了構造函數 constructor 和定義在原型對象上的函數 myAge()(注意沒有 function關鍵字)
* 這樣就避免了Student.prototype.hello = function () {...}這樣分散的代碼
*/
class Student {
// 父類的構造函數
constructor (name) {
this.name = name
}
hello () {
console.log('Hello ' + this.name)
}
}
class PrimaryStudent extends Student{
construct(name,age){
// 子類 PrimaryStudent 的構造函數中的 super(),代表調用父類的構造函數
super(name)
this.age = age
}
myAge(){
console.log('my age is ' + this.age)
}
}
// 當子類 PrimaryStudent 被實例化時,它指向的是子類 PrimaryStudent 的構造函數,而不是父類 Student 的構造函數。
// 所以說,“ super() 內部的 this 指向子類 ”
let xiaohong = new PrimaryStudent('小紅',18);
console.log(xiaohong.name)//小紅
xiaohong.myAge()//my age is 18
- (1)
PrimaryStudent
的定義也是 class關鍵字 實現的,而extends
則表示原型鏈對象來自Student。 - (2)子類的構造函數可能會與父類不太相同,例如: PrimaryStudent 需要 name 和 grade 兩個參數,並且需要通過 super(name) 來調用父類的構造函數,否則父類的 name屬性 無法正常初始化。
super() 關鍵字
super()
雖然代表了父類的構造函數,但是返回的卻是子類的實例,內部this的指向是子類的實例,因此這裏的 super() 相當於 Student.prototype.constructor.call(this)。
鏈接- super 大介紹
構造函數生成實例的執行過程:
- 1、當使用了構造函數,並且 new 構造函數(),後臺會隱式執行 new Object() 創建對象;
- 2、將構造函數的作用域給新對象,(即new Object() 創建出的對象),而函數體內的this就代表new Object() 出來的對象;
- 3、執行構造函數的代碼‘’
- 4、返回新對象(後臺直接返回);
二、數組處理
- 1、數組轉字符串- join()
- 2、字符串轉數組- split(",")
// 拿到數組的最後一個元素
let date = []
date = res.data.data;
let last = date.slice(-1);