静 态 方 法 :
- 什么是静态方法?
- 有 static关键字,表明该方法是一个静态方法。
- 需要通过类名来调用, 而不是在实例(this)上调用。
- 如果使用this调用,或者在该方法中使用this。 均会出现异常。
- 静态方法可以和非静态方法重名 (不推荐这样)。
- 父类的静态方法,可以被子类继承。
演示代码:
<script>
{
class Person{
//实例属性的新写法, 位置放在类的顶部
num = "我是实例属性的新写法";
// 静 态 属 性
// 写法: 在实例属性前, 加static关键字
static Admin = "开机密码";
constructor(num_a,num_b) {
//实例属性
//绑定这里可以让全局都能找到
this.num_a = num_a;
this.num_b = num_b;
}
//关键字
static sum(){
// return this.num_a > this.num_b ? this.num_a : this.num_b;
return "hello";
}
newStr(){
// return `我是很大的那个${this.sum()}`
console.log(`我是很大的那个${Person.sum()}和${this.num}`);
}
}
console.log(Person.sum());
//用new实例化一个对象
let person = new Person(20,50);
// console.log(person.sum());
// console.log(person.newStr());
person.newStr();
console.log(Person.Admin);
}
static sum(){
// return this.num_a > this.num_b ? this.num_a : this.num_b;
return "hello";
}
newStr(){
// return `我是很大的那个${this.sum()}`
console.log(`我是很大的那个${Person.sum()}和${this.num}`);
}
}
console.log(Person.sum());
let person = new Person(20,50);
// console.log(person.sum());
// console.log(person.newStr());
person.newStr();
console.log(Person.Admin);
}
static sum(){
// return this.num_a > this.num_b ? this.num_a : this.num_b;
return "hello";
}
newStr(){
// return `我是很大的那个${this.sum()}`
console.log(`我是很大的那个${Person.sum()}和${this.num}`);
}
}
console.log(Person.sum());
let person = new Person(20,50);
// console.log(person.sum());
// console.log(person.newStr());
person.newStr();
console.log(Person.Admin);
}
</script>