1.JS中的类的生成及继承
S中类用class关键字表示,
类中的几个关键1.构造函数constructor;2.静态数据 :static;3.私有数据:# 4.方法;5.访问器函数 get set;6.继承:extends 继承中super的使用
1.1类的生成
console.log("-------------------------------");
console.log("形成一个User的类\n");
let User = class{
constructor(name ,address,favorite){
this.name = name;
this.address = address;
this.favorite = favorite;
}
static gender = "male";
getUserInfo(){
return `你的姓名是:${this.name}\n你的地址是:${this.address}\n你的爱好是:${this.favorite}\n`;
}
}
let me = new User("jiao","peking","reading");
console.log(me.getUserInfo());
1.2 类的继承 extends
class Child extends User {
constructor(name,address,favorite,tel){ //把父类的全部属性写上
super(name,address,favorite);
this.tel = tel;
}
// 继承父类的方法
getUserInfo(){
return `${super.getUserInfo()}您的电话是:${this.tel}`;
}
}
let child_1 = new Child("wang","hefei","sport","1388");
console.log(child_1.getUserInfo());
1.3 类的访问器属性
class Descendent extends Child{
constructor(name,address,favorite,tel,age){
super(Child);
this.age= age;
}
#gender = "male";
get gender() {
return this.#gender;
}
set gender(a) {
this.#gender = a;
}
}
let des_1 = new Descendent("li","sd","reading","323",32);
console.log(des_1.gender);
console.log("变换gender的值");
des_1.gender = "female";
console.log(des_1.gender);
2.字符串中常用的API
let str = "hello the world ";
let str_2 ="again";
// 2.1indexOf查找字符串中某个字符第一次出现的位置;
console.log(str.indexOf("l"));
// 2.2 concat合并两个字符串
console.log(str.concat(str_2));
// 2.3 slice() 获得指定位置之后的片段字符
console.log(str.slice(3))
// 2.4 replace( ),取代字符串中的某些字符
console.log(str.replace("the","my"));
// 2.5 匹配字符中的某些字符
console.log(str.match(/the/));
console.log('--------------------------');
3.数组常用的API
console.log("数组常用的API");
let arr_1 = [1,2,30,23];
let arr_2 = [4,5];
//3.1 求和 reduce
console.log(arr_1.reduce((acc,cur)=> acc + cur));
// 3.2. 遍历 map() 并返回数组
let arr_map = arr_1.map(cur => cur +=2);
console.log(arr_map);
// 3.3 concat()合并数组
console.log(arr_1.concat(arr_2));
// 3.4 取得数组中的片段
console.log(arr_1.slice(2));
// 3.5 数组扩项与减项 pop push
console.log(arr_1.pop(3));
console.log(arr_1);
console.log(arr_1.push(45));
console.log(arr_1);