es6解读4: 类

类的基本定义和生成实例:class

class Parent{
    constructor(name='leilei'){
        this.name=name;
    }
}
let v_parent=new Parent('ymy');
console.log(v_parent.name) //ymy

类的继承 :extends

class Parent{
    constructor(name='leilei'){
        this.name=name;
    }
}
class Child extends Parent{
    //继承:子类怎么在自己的构造函数中传递参数
    constructor(name='child'){
        super(name);//如果不传参,子类使用的是父类默认的参数;super一定放在构造函数的第一行;
        this.type='child';
    }
}
console.dir(new Child('hello'))  //Child类 ==> name='hello',type='child'

类中的getter 和 setter

  • 分别用来设置属性和获取属性
class Parent{
  constructor(name='leilei'){
      this.name=name;
  }
  get longName(){
      return 'ymy '+this.name;
  }
  set longName(value){
      this.name=value;
  }
}
// 创建实例
let p1=new Parent();
console.log(p1.longName) //获取属性 ymy leilei
p1.longName='tangtang'; //设置属性
console.log(p1.longName) //获取属性 ymy tangtang

给类中添加静态方法 static

  • 注意:static属性只能用来设置类的静态方法,不能用来设置类的静态属性
  • 类的静态属性只能通过: 类.key=value;来设置
  • 类的静态方法,只有类能使用,实例不能使用,实例只能使用原型上的属性和方法;
class Parent{
  constructor(name='leilei'){
      this.name=name;
  }
  //设置静态方法
  static tell(){
      console.log('tell');
  }
}
Parent.sex='gril';  //设置类的静态属性
Parent.tell() //调用类的静态方法; tell

类的 prototype 属性和proto属性

大多数浏览器的 ES5 实现之中,每一个对象都有__proto__属性,指向对应的构造函数的prototype属性
。Class 作为构造函数的语法糖,同时有prototype属性和__proto__属性,因此同时存在两条继承链。

(1)子类的__proto__属性,表示构造函数的继承,总是指向父类。

(2)子类prototype属性的__proto__属性,表示方法的继承,总是指向父类的prototype属性。
class A {
}

class B {
}

// B 的实例继承 A 的实例
Object.setPrototypeOf(B.prototype, A.prototype);
// 等同于
B.prototype.__proto__ = A.prototype;

// B 的实例继承 A 的静态属性
Object.setPrototypeOf(B, A);
// 等同于
B.__proto__ = A;

const b = new B();
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容