ES6 -类和继承

一、类

1.格式

class Person{
    // 构造方法,调用new,自动执行
    constructor(name,age){
        this.name=name;
        this.age=age;
    }
    // 等价于 Person.prototype.showname
    showname(){
        console.log(`名字是${this.name}`);
    }
}

let p1=new Person('aaaa',12);
// 表达式形式
const Person=class{
    // 构造方法,调用new,自动执行
    constructor(name,age){
        this.name=name;
        this.age=age;
    }
 
}

let p1=new Person('aaaa',12);
// 变量定义方法名
let aaa='ssss';
class Person{
    // 构造方法,调用new,自动执行
    constructor(name,age){
        this.name=name;
        this.age=age;
    }
    // 变量定义方法名
    [aaa](){
        return 'ok'
    }
}

let p1=new Person('aaaa',12);
console.log(p1[aaa]());//ok
console.log(p1.ssss());//ok
// class没有提升功能
let p1=new Person('aaaa',12);//error:Person is not defined
class Person{
    // 构造方法,调用new,自动执行
    constructor(name,age){
        this.name=name;
        this.age=age;
    }
}

3.this的指向

class Person{
    constructor(name,age){
        this.name=name;
        this.age=age;
        // 改变this指向
        this.showname=this.showname.bind(this);
    }
    showname(){
        console.log(this);
        console.log(`名字是${this.name}`);
    }
}
let p1=new Person('aaaa',12);

let {showname}=p1;

showname();

 4.Class 的取值函数(getter)和存值函数(setter)

class Person{
    constructor(){
       
    }
    set aaa(val){
        console.log(`设置aaa属性,值为${val}`)
    }
    get aaa(){
        return 'ass';
    }
}
let p1=new Person();
p1.aaa=123; //设置aaa属性,值为123

console.log(p1.aaa);//ass

5.class 的静态方法

// 静态方法:类身上的方法 static 

class Person{
    constructor(){
       
    }
    static test(){
        console.log('静态方法');
    }
}
Person.test();//静态方法

二、继承:Class 可以通过extends关键字实现继承

  super这个关键字,既可以当作函数使用,也可以当作对象使用

// 父类
class Person{
    constructor(name){
        this.name=name;
    }
    showname(){
        console.log(this.name);
    }
}
// 子类
class Student extends Person{
    constructor(name,grade){
        super(name);//super指代父级 super作为函数调用时,代表父类的构造函数,super()只能用在子类的构造函数之中
        this.grade=grade;
    }
    showname(){
        super.showname();//父级的方法执行 super作为对象时,在普通方法中,指向父类的原型对象;在静态方法中,指向父类。
        console.log('子类');
    }
    showgrade(){
        console.log(this.grade);
    }
}

let stu1=new Student('aaa','一年级');
stu1.showname();//aaa 子类
stu1.showgrade();//一年级
// super指向父类的原型对象,所以定义在父类实例上的方法或属性,是无法通过super调用的

class A {
  constructor() {
    this.p = 2;
  }
  
}

class B extends A {
  get m() {
    return super.p;
  }
}

let b = new B();
b.m // undefined
// 如果super作为对象,用在静态方法之中,这时super将指向父类,而不是父类的原型对象。
class Parent {
  static myMethod(msg) {
    console.log('static', msg);
  }

  myMethod(msg) {
    console.log('instance', msg);
  }
}

class Child extends Parent {
  static myMethod(msg) {
    super.myMethod(msg);
  }

  myMethod(msg) {
    super.myMethod(msg);
  }
}

Child.myMethod(1); // static 1

var child = new Child();
child.myMethod(2); // instance 2

猜你喜欢

转载自www.cnblogs.com/yuesu/p/9541612.html