ES6中定义的类和对象

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


// 类的基本定义和生成实例
     class Parent{ //定义一个类
        constructor(name='xiaxaioxian'){
          this.name= name;
        }
     } 

// 生成一个实例
     let g_parent = new Parent();
     console.log(g_parent); //{name: "xiaxaioxian"}
     let v_parent = new Parent('v') // 'v'就是构造函数name属性 , 覆盖构造函数的name属性值
     console.log(v_parent);  // {name: "v"}

继承


 // 继承
    class Parent{ //定义一个类
        constructor(name='xiaxaioxian'){
          this.name= name;
        }
    } 

    class Child extends Parent{

    }

    console.log('继承',new Child()) // 继承 {name: "xiaxaioxian"}

继承传递参数


// 继承传递参数
    class Parent{ //定义一个类
        constructor(name='xiaxaioxian'){
          this.name= name;
        }
    } 

    class Child extends Parent{
      constructor(name = 'child'){ // 子类重写name属性值
        super(name); // 子类向父类修改 super一定放第一行
        this.type= 'preson';
      }
    }

    console.log('继承',new Child('hello')) // 带参数覆盖默认值  继承{name: "hello", type: "preson"}

ES6重新定义的ES5中的访问器属性


class Parent{ //定义一个类
        constructor(name='xiaxaioxian'){
          this.name= name
        }

        get longName(){ // 属性
          return 'mk' + this.name
        }

        set longName(value){
          this.name = value
        }
    }

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

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

类的静态方法:

   
class Parent{ //定义一个类
      constructor(name='xiaxaioxian'){
        this.name= name
      }

      static tell(){ // 静态方法:通过类去调用,而不是实例
        console.log('tell')
      }
    }


    Parent.tell(); // tell

类的静态属性:


// 静态属性
    class Parent{ //定义一个类
      constructor(name='xiaxaioxian'){
        this.name= name
      }


      static tell(){ // 静态方法:通过类去调用,而不是实例
        console.log('tell')  // tell
      }
    }


    Parent.type = 'test'; // 定义静态属性


    console.log('静态属性',Parent.type) // 静态属性 test


    let v_parent = new Parent();
    console.log(v_parent); // {name: "xiaxaioxian"}  没有tell方法和type属性


  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值