类的定义
class Animal {
//构造函数,创建这个类时会执行的函数
constructor(color){
//this当前对象
console.log("构造")
this.color=color
}
}
const myCat = new Animal("白");
console.log(myCat)
- constructor: 构造函数
- this : 当前实例
- super: 它的父类
类的继承 class Cat extends Animal
<script>
class Animal {
constructor(color) {
this.color = color
}
eat() {
console.log('爱吃鱼');
}
}
class Cat extends Animal {
constructor(color, name) {
super(color)
this.name = name
}
}
let myCat = new Cat('黑白', '皮皮')
myCat.eat()
console.log(myCat.color)
console.log(myCat.name)
</script>
通过static关键字可以声明静态的方法,静态方法归属于类而不是实例 也可声明静态变量
普通的方法归属于实例,需要通过实例调用
<script>
class Animal {
//IE不识别静态属性
static props = {
name:"啦啦啦"
}
constructor(color,name){
this.color = color;
this.name = name;
}
//通过static关键词可以声明静态方法,静态方法属于类而不是实例
static getName (){
console.log('静态方法')
return this
}
eat (){
console.log(this.name+'爱吃鱼')
}
}
let bigCat = new Animal('黑白','皮皮')
let smallCat = new Animal('白花', '球球')
bigCat.eat();
smallCat.eat();
console.log(Animal.getName())
console.log(Animal.props.name)
</script>