继承小练习
{
class Person{
constructor(num_a,num_b){
this.num_a = num_a; //同绑定this
this.num_b = num_b;
}
sum(){ //通过this
return this.num_a > this.num_b ? this.num_a : this.num_b
}
newStr(){
return `我是最大的值${this.sum()}`
}
}
let person = new Person(20,50)
console.log(person.sum()) //输出50
}
静 态 方 法
方法前:
- 有 static关键字,表明该方法是一个静态方法
- 需要通过类名来调用, 而不是在实例(this)上调用
- 如果使用this调用,或者在该方法中使用this。 均会出现异常
- 静态方法可以和非静态方法重名 (不推荐这样)
- 父类的静态方法,可以被子类继承
{
class Person{
//实例属性新写法 写到constructor外面 顶部
num = "新写法"; //不需要写this
// 静 态 属 性
// 写法(旧): 在实例属性前, 加static关键字
static Admin = "开机密码";
constructor(num_a,num_b){
this.num_a = num_a; //同绑定this
this.num_b = num_b;
}
static sum(){
return 'hello' //内部调用 在使用静态的方法时 这里不能使用this
}
newStr(){
// console.log(`我是最大的值${Person.sum()}`) //内部调用
console.log(`我是最大的值${Person.sum()}和${this.num}`)
}
}
let person = new Person(20,50)
// console.log(person.newStr())//外部调用
person.newStr(); //内部
console.log(Person.Admin)
}