Home > Web Front-end > JS Tutorial > body text

Explanation and application of classes and objects in ES6

零下一度
Release: 2017-06-25 09:26:50
Original
1324 people have browsed it

1. Basic definition and generated examples

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

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());
}
Copy after login

 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'));
}
Copy after login

 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);
}
Copy after login

 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);


}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!