类
class Person{
constructor(name="dg",age=60){
this.name=name;
this.age=age;
}
showMSG(){ //定义在原型上
console.log(this.age,this.name)
}
print(){ //定义在原型上
console.log('xxx')
}
}
var person1=new Person();
console.log("+++++++++",Person.prototype.showMSG==person1.showMSG); // true 我们来判断一下person1.showMsg()是不是写在原型链上
类的表达式
var demo = class {
constructor(name, age){
this.name = name;
this.age = age;
}
say(){
console.log('my name is ' + this.name + ', ' + this.age + ' years old');
}
}
console.log(demo);
var person = new demo('payen', '19'); <-- 注意
person.say(); //my name is payen, 19 years old
类的继承
// 提醒: 说起es5的继承,是通过prototype进行继承,在es6里,通过extends关键字,就可以实现继承的效果。
// 定义父类:
class A{
constructor(x,y){
this.x=x;
this.y=y
}
toString(){
console.log("++++++++++++",this.x ,this.y); // 2,3
}
}
var fp=new A(2,3);
fp.toString();
// 定义子类
class B extends A{
constructor(x,y,z){
super(x,y); // 用super调用父类的构造函数
super.toString() // 调用父类的方法
this.z=z;
}
toString(){
console.log("++++++++++++",this.x ,this.y,this.z);
}
}
var b=new B(4,5,6)
b.toString(); // 4,5,6
关于super:
子类中有constructor,内部就要有super,因为子类没有自己的this对象,需要继承父类的this对象再添加东西,super指代父类的实例(父类的this对象)
这里的super(x,y)就是调用父类的构造函数
super.toString()就是调用父类toString()方法
super虽然代表了父类A的构造函数,但是返回的是子类B的实例
静态方法
class C{
constructor(){
this.name="lichuyan"
}
static print(){
console.log("++++++++++”);
}
}
C.print();
static注意:
1:所有类中定义的方法都会被实例继承,如果再类方法前加static,就不会被实例继承,而是通过类来调用
2:静态方法也可以从super调用,子类调用父类的staic方法只能在静态函数中调用
class C{
constructor(){
this.name="lichuyan"
}
static print(){
console.log("++++++++hello++");
}
}
C.print();
class D extends C{
static say(){
super.print();
}
}
D.say();