Correcting teacher:PHPz
Correction status:qualified
Teacher's comments:完成的不错, 继续加油
// 先声明一个类
let User = class{
// 构造函数 声明属性
constructor(name,age){
// 1.实例成员
this.name = name
this.age = age
}
// 2.方法
sayHello(){
return `你好,我是${this.name},今年${this.age}岁,性别${User.gender},我是${User.country}人`
}
// 在类中添加静态成员
static gender = "男";
}
// 在类外添加静态成员
User.country = "China"
// 实例化
const user = new User('阿狗', 27)
console.log(user);
console.log(user.sayHello());
console.log("----------------------");
// extends 继承
class Child extends User {
constructor(name,age,hobby){
super(name,age)
// 子类扩展属性 hobby
this.hobby = hobby
}
sayHello(){
return `${super.sayHello()},我的爱好是${this.hobby}`
}
}
const child = new Child("二狗",18,"打飞机")
console.log(child.sayHello());
console.log('=====================');
// 字符串常用api
let str = "我爱的人不是我的爱人";
// 1.取长度
console.log(str.length);
// 2.查询成员的索引
console.log(str.indexOf('爱'));
// 爱出现了两次 只返回第一个查到的值 若想查到所有的索引 可看下列代码
function findAll(Str,str) {
let res =[],
len =Str.length,
index=0
while(index < len){
// 由于我需要将str每个都传入进去 所以我需要将索引也进行更新
index = Str.indexOf(str,index)
if(index === -1){
break;
}
res.push(index)
index ++
}
return res
}
console.log(findAll(str,"爱"));
// 3.替换 replace
let str1 = str.replace('爱',"不爱")
console.log(str1);
// 批量替换 replaceAll
let str2 = str.replaceAll('爱',"不爱")
console.log(str2);
// 4.寻找索引的值 substring()
console.log(str.substring(1,3));
console.log(str.substring(5,3));
// 5.字符串 转 数组 split
let str3 = str.split("")
console.log(str3);
// 例子
let Phone = class{
#founder = 'Q';
constructor(name,price){
this.name = name
this.price = price
}
introduce(){
return `这款手机名叫${this.name},他的价格是${this.price},我们现在有iphone的${Phone.PhoneModel}的型号`
}
who(){
return `CE0是${this.#founder}`
}
changeCEO(founder){
this.#founder = founder
}
static PhoneModel =[4,5,6,7,8,9,10,11,12,13,14]
}
const phone = new Phone()
console.log(phone.who());
phone.changeCEO("k")
console.log(phone.who());
class Phone13 extends Phone{
constructor(name,price,inventory){
super(name,price)
this.inventory = inventory
}
introduce(){
return `${super.introduce()},库存还有${this.inventory}部`
}
}
const phone13 = new Phone13('iphone13','8000',500)
console.log(phone13.introduce());
console.log(phone13.founder);//无法访问父类的私有属性 返回undefined