Blogger Information
Blog 34
fans 0
comment 0
visits 20042
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
类简化构造函数创建对象及解构赋值
OC的PHP大牛之路
Original
280 people have browsed it

用类来简化构造函数创建对象的过程

js类就是函数

ES6 class

  1. // class 声明类
  2. class Demo1{
  3. // 公共成员
  4. username='朱老师';
  5. // 构造方法,实例初始化
  6. constructor(name,email){
  7. // 自由属性
  8. this.name=name;
  9. this.email=email;
  10. }
  11. // 共享成员:原型成员
  12. getInfo(){
  13. return`${this.name}:(${this.email})`;
  14. }
  15. // 静态成员
  16. static status='enabled';
  17. }
  18. // 公共成员和静态成员都有(;)但构造方法和共享成员后面不能有
  19. const obj1=new Demo1('朱老师','zhu@php.cn');
  20. console.log(obj1.getInfo());
  21. // 访问静态成员
  22. console.log(Demo1.status);

继承

  1. // 继承(extends)
  2. class Demo2 extends Demo1{
  3. // 构造器
  4. // sex为当前子类的扩展自定义属性
  5. constructor(name,email,sex){
  6. super(name,email);
  7. this.sex=sex;
  8. }
  9. // 子类对父类的方法进行扩展
  10. getInfo(){
  11. return `${super.getInfo()},${this.sex}`;
  12. }
  13. }
  14. const obj2=new Demo2('欧阳','oy@php.cn','男');
  15. console.log(obj2.getInfo());

访问器属性

  1. // 访问器属性
  2. class Demo3{
  3. age=30;
  4. get age(){
  5. return this.age;
  6. }
  7. set age(value){
  8. this.age=age;
  9. }
  10. }
  11. // 实例化
  12. const obj3=new Demo3();
  13. console.log(obj3.age);

解构赋值

  1. const user=['朱老师','zhu@php.cn'];
  2. let username=user[0];
  3. let useremail=user[1];
  4. console.log(username,useremail);

数组解构

  1. // 数组解构
  2. // 模板=值(数组)
  3. let [username,useremail]=['朱老师','zhu@php.cn']
  4. console.log(username,useremail);
  5. // 更新
  6. [username,useremail]=['苟老师','gou@php.cn']
  7. console.log(username,useremail);
  8. // 参数不足,默认值
  9. [username,useremail,age=30]=['苟老师','gou@php.cn']
  10. console.log(username,useremail,age);
  11. // 参数过多,...rest
  12. [a,b,c,...arr]=[1,2,3,4,5,6,7,8,9]
  13. console.log(a,b,c);
  14. console.log(arr);

对象解构

  1. // 对象结构
  2. let {id,lesson,score}={id:1,lesson:'js',score:88};
  3. console.log(id,lesson,score);
  4. // 更新(用一对大括号把整个表达式包装起来)
  5. ({id,lesson,score}={id:2,lesson:'php',score:98});
  6. console.log(id,lesson,score);
  7. // 左模板中的变量存在命名冲突就给冲突的变量起个别名
  8. let {id:itemId,num,price}={id:123,num:10,price:888};
  9. console.log(itemId,num,price);
Correcting teacher:PHPzPHPz

Correction status:qualified

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post