美文网首页
(二)17.类19-08-15

(二)17.类19-08-15

作者: 你坤儿姐 | 来源:发表于2019-08-15 11:11 被阅读0次
{
  // 基本定义和生成实例

  //构建类 类的基本定义
  class Parent{
    constructor(name='mukewang'){
      this.name=name;
    }
  }
  //生成实例
  let v_parent=new Parent('v');
  console.log('构造函数和实例',v_parent);
}

打印结果:
构造函数和实例 e {name: "v"}

{
  //继承传递参数
  class Parent{
    constructor(name='mukewang') {
      this.name=name;
    }
  }

  //通过extends关键词继承Parent
  class Child extends Parent{

  }
  console.log('继承',new Child());
}

打印结果:
继承 t {name: "mukewang"}

{
  //继承传递参数
  class Parent{
    constructor(name='mukewang') {
      this.name=name;
    }
  }

  //通过extends关键词继承Parent
  class Child extends Parent{

    //在子类的构造函数中使用一个super方法 改变父类的值
    constructor(name='child'){
      //super传递的是父类的参数,如果括号内为空默认传递的是父类的默认值
      super(name);
      //如果子类还要增加自己的属性 一定要写在super方法下方 不然会报错
      this.type='child';
    }
  }
  console.log('继承传递参数',new Child('hello'));
}

打印结果:
继承传递参数 t {name: "hello", type: "child"}

getter setter

{
  //getter setter
  class Parent{
    constructor(name='mukewang'){
      this.name=name;
    }

    //这里是读取属性 不是函数
    get longName(){
      return 'mk'+this.name
    }
    //set 赋值  给longName赋值这里会把这个值给name
    set longName(value){
      this.name=value;
    }
  }

  let v=new Parent();
  console.log('getter',v.longName);//getter的作用

  v.longName='hello';
  console.log('setter',v.longName);
}

打印结果:
getter mkmukewang
setter mkhello

  • 类的静态方法
{
  //类的静态方法
  class Parent{
    constructor(name='mukewang'){
      this.name=name;
    }

    //加了static这个方法就变成了静态方法
    static  tell(){
      console.log('tell');
    }
  }

  Parent.tell();
}

打印结果:tell

  • 静态属性
{
  //静态属性
  class Parent{

    constructor(name='mukewang'){
      this.name=name;
    }
    // static  tell(){
    //   console.log('tell');
    // }

  }

  Parent.type='test';
  console.log('静态属性',Parent.type);
}

打印结果:
静态属性 test

相关文章

网友评论

      本文标题:(二)17.类19-08-15

      本文链接:https://www.haomeiwen.com/subject/cisajctx.html