Home >Web Front-end >JS Tutorial >Explanation and application of classes and objects in ES6

Explanation and application of classes and objects in ES6

零下一度
零下一度Original
2017-06-25 09:26:501370browse

1. Basic definition and generated examples

{  // 基本定义和生成实例  class Parent{
    constructor(name='mukewang'){//构造器,初始化一些参数      this.name=name;
    }
  }
  let v_parent=new Parent('v');
  console.log('构造函数和实例',v_parent);
}

2. Inheritance (via extends Direct subclasses inherit parent classes)

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

  class Child extends Parent{

  }

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

 Inheritance passes its own parameters (note: you can use super() to use your own attributes, and super must be placed First line)

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

  class Child extends Parent{
    constructor(name='child'){
      super(name);      this.type='child';
    }
  }

  console.log('继承传递参数',new Child('hello'));
}

 Getters and setters in the class

{  // getter,setter  class Parent{
    constructor(name='mukewang'){      this.name=name;
    }
  //注意下面的longName是属性而不是方法
    get longName(){      return 'mk'+this.name
    }

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

  let v=new Parent();
  console.log('getter',v.longName);
  v.longName='hello';
  console.log('setter',v.longName);
}

 Static methods and static properties

{  // 静态方法 使用static声明 注意:静态方法只能通过类来调用,而不能通过类的实例进行调用,相当于es5中的私有方法  class Parent{
    constructor(name='mukewang'){      this.name=name;
    }

    static tell(){
      console.log('tell');
    }
  }

  Parent.tell();

}

{  // 静态属性 直接类名通过.来声明一个静态属性  class Parent{
    constructor(name='mukewang'){      this.name=name;
    }

    static tell(){
      console.log('tell');
    }
  }

  Parent.type='test';

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


}

The above is the detailed content of Explanation and application of classes and objects in ES6. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn