class Animal{
constructor(name,age){
this.name=name;
this.age=age;
}
run(){
alert(this.name+"run");
}
static run2(){
alert(222);
}
}
var dog=new Animal("dog",3);
dog.run();
Animal.run2();
class命名类,类首字母大写;
constructor函数就相当于是es5里的构造函数,定义属性;
不加static方法就相当于是es5里在原型上扩充的方法,被实例化对象调用;在方法的前面加上static关键字这个方法就变成了静态方法,被整个类调用,不能被实例化对象调用。this不再指向实例化对象,而是整个类。
es5实现继承的方法:
1、call()和apply();
2、直接改变prototype;
3、比如dog继承animal类
dog.prototype=new Animal();
Dog.prototype.constructor=Dog;
es6中添加了专门用来实现继承的关键字 extends super
cat继承animal类 animal类是父类,也叫作超类;
class Cat extends Animal{
constructor(name,age,miao){
spuer(name,age);
this.miao=miao;
}
say(){
alert(this.name+"喵");
}
}
var cat1=new Cat("小花",2,"猫叫");
cat1.say();
cat1.run();