JavaScript-----类
1.类的定义
类的定义和调用类中的方法如下代码:
class Dog{
constructor(Name,age) {
this.Name=Name;
this.age=age;
}
Age(){//注意这里的Age 不能是age 否则会和变量冲突
console.log("这个类中的方法被调用了!");
}
}
var d=new Dog("张三",18);
d.Age(); //执行Age方法
2.类的继承
继承的关键字extends,代码如下:
class Animal{
constructor(name){
this.Name=name;
}
animal(){
console.log("动物:"+this.Name);
}
}
class Dog extends Animal{
constructor(name,eat){
super(name); //name给父类的构造
this.eat=eat;
this.name=name;
}
Eat() {
console.log(this.name+" "+"在吃:"+this.eat);
}
}
var D=new Dog("狗","狗粮");
D.animal();//输出 动物:狗
D.Eat();//输出 狗 在吃:狗粮
2.1 静态static的用法
//static 只能用于类中的方法
class preson{
static Age(){
console.log("调用了一个静态方法!");
}
Name(){
console.log("这是一个普通的方法");
}
}
preson.Age();
// preson.Name(); 不是静态方法 是不能调用的
new preson().Name(); //普通方法的调用