/**
* 类class(类的概念)
*
*/
{ // 基本定义和生成实例
class Parent{ //声明类
//声明构造函数
constructor(name='mukewang'){
this.name=name;
}
}
let v_parent=new Parent('v');
console.log('构造函数和实例',v_parent); //v
}
{ // 继承
class Parent{ //父类
constructor(name='mukewang'){
this.name=name;
}
}
//子类集成父类
class Child extends Parent{
}
console.log('继承',new Child()); //
}
{ // 继承传递参数(子类覆盖父类的值)
class Parent{ //父类
constructor(name='mukewang'){
this.name=name;
}
}
class Child extends Parent{
constructor(name='child'){
/**
* 注意: 1.super()一定要放在构造函数的第一行
* 2.super()传递覆盖父类的参数列表
* 3.一般用于覆盖父类的默认属性或函数
*/
super(name); //使用super() 修改父类的值
this.type='child';
}
}
console.log('继承传递参数',new Child('hello')); //hello child
}
{ // 类中的getter,setter
class Parent{
constructor(name='mukewang'){
this.name=name;
}
get longName(){ //get属性
return 'mk'+this.name
}
set longName(value){ //set属性
this.name=value;
}
}
let v=new Parent();
console.log('getter',v.longName); //mkmukewang
v.longName='hello';
console.log('setter',v.longName); //mkhello
}
/**
* 静态方法,是通过类去调用,而不是通过类的实例去调用
*/
{
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); //调用静态属性(通过类去调用)
}
012-类class(类的概念)
最新推荐文章于 2022-04-27 18:32:29 发布