zoukankan      html  css  js  c++  java
  • 类和对象

    1.基本定义和使用

    1 {
    2     class Parent{
    3         constructor(name='zyn'){
    4             this.name=name;
    5         }
    6     }
    7     var pp = new Parent('zyn...');
    8     console.log('构造函数实例',pp)
    9 }

    2.继承 extends 

     1 {
     2     class Parent{
     3         constructor(name='zyn'){
     4             this.name=name;
     5         }
     6     }
     7     class Child extends Parent{
     8 
     9     }
    10     console.log('继承',new Child())
    11 }

    3.继承传递参数,super

     1 {
     2     class Parent{
     3         constructor(name='zyn'){
     4             this.name=name;
     5         }
     6     }
     7     class Child extends Parent{
     8         constructor(name='child'){
     9             super(name);  //super中是父元素的属性列表,如果子类需要增加属性,super需要放在最前面
    10             this.type='cc';
    11         }
    12     }
    13     console.log('继承传递参数',new Child(),new Child('hello'))
    14 }

    4.getter,setter

     1 {
     2     class Parent{
     3         constructor(name='zyn'){
     4             this.name=name;
     5         }
     6         get longName(){   //注意是属性,虽然写法像函数
     7             return 'zz'+this.name;
     8         }
     9         set longName(value){
    10             this.name=value
    11         }        
    12     }
    13     let vv =new Parent();
    14     console.log('getter',vv.longName);
    15     vv.longName='zzzzzHello';
    16     console.log('setter',vv.longName)
    17 }

    5.静态方法,通过类调用,而不是类的实例

     1 {
     2     // 静态方法,通过类调用,而不是类的实例
     3     class Parent{
     4         constructor(name='zyn'){
     5             this.name=name;
     6         }
     7         static tell(){
     8             console.log('tell')
     9         }
    10     }
    11     Parent.tell(); //tell
    12 }

    6.静态属性直接定义在类上

     1 {
     2     // 静态属性
     3     class Parent{
     4         constructor(name='zyn'){
     5             this.name=name;
     6         }
     7         static tell(){
     8             console.log('tell')
     9         }
    10     }
    11 
    12     Parent.type='test';  //静态属性直接在类上定义
    13     console.log('静态属性',Parent.type)
    14 }
  • 相关阅读:
    常用的20个正则表达式
    关于position:fixed;的居中问题
    Html table 合并单元格
    JS异步加载的三种方式
    DOM事件代码小结
    用js写一个回车键盘事件
    JavaScript 常用方法总结
    可拖拽进度条
    js数组拍平
    js验证码倒计时
  • 原文地址:https://www.cnblogs.com/zynkl1314/p/12056266.html
Copyright © 2011-2022 走看看