ES6之类Class

{
   class Ploygon {
       constructor(width, height)
       {
           this.width = width;
           this.height = height;
       }
       get area() {
           return this.countArea();
       }
       countArea() {
           return this.width * this.height;
       }
   };

   let result = new Ploygon(10, 20);
   console.log(result.area);
}

说明


  • constructor()方法:该方法是类的默认方法,通过 new 创建对象实例时,自动调用该方法;该方法默认返回实例对象(即this)
  • get关键字的用法:有时候访问属性时能返回一个动态计算后的值;不希望通过使用明确的方法调用来显示内部变量的状态
{
   class Point {
       constructor(x, y)
       {
           this.x = x;
           this.y = y;
       }

       static distance(a, b) {
           const dx = a.x - b.x;
           const dy = a.y - b.y;

           return Math.sqrt(dx*dx + dy*dy);
       }
   };

   const pOne = new Point(5, 5);
   const pTwo = new Point(10, 10);

   console.log(Point.distance(pOne, pTwo));
}

说明


  • static关键字:用来定义类的静态方法;该方法不会被实例所继承,只能通过类名来调用;静态方法经常用来作为 工具函数 使用;
  • 子类可以调用父类的静态方法
{
   class People {
       constructor(name)
       {
           this.name = name;
       }

       sayName() {
           console.log(this.name);
       }
   };

   class Student extends People {
       constructor(name, grade)
       {
           super(name);
           this.grade = grade;
       }

       sayGrade() {
           console.log(this.grade);
       }
   };

   const stu = new Student('adiu', '幼儿园');
         stu.sayGrade();
         stu.sayName();
}

说明


  • 子类可以继承父类的所有属性和方法
  • supper()方法调用父类的构造函数(即父类的** this **);子类必须在constructor方法中调用 supper() ,否则新建实例时会报错 this is not defined ,这是因为子类没有自己的 this对象,而是继承父类的this对象,然后对其进行加工;如果不调用super方法,子类就得不到this对象
{
   class People {
       constructor(name)
       {
           this.name = name;
       }

       get name() {
           return this._name.toString().toUpperCase();
       }

       set name(name) {
           this._name = name;
       }

       sayName() {
           console.log(this.name);
       }
   };

   const result = new People('adiu');
   console.log(result.name);
   console.log(result._name);
   result.sayName();
}

说明


  • 在class内部使用 getset 关键字,对某个属性设置取值和赋值函数(定义读写器),拦截该属性的存取行为
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • class的基本用法 概述 JavaScript语言的传统方法是通过构造函数,定义并生成新对象。下面是一个例子: ...
    呼呼哥阅读 9,569评论 3 11
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 33,738评论 18 399
  • 1.import static是Java 5增加的功能,就是将Import类中的静态方法,可以作为本类的静态方法来...
    XLsn0w阅读 5,147评论 0 2
  • 面向对象主要针对面向过程。 面向过程的基本单元是函数。 什么是对象:EVERYTHING IS OBJECT(万物...
    sinpi阅读 4,826评论 0 4
  • 加油,诺诺,考场一瞻卷子,羞涩起嘿嘿。
    waterfront阅读 1,270评论 0 0

友情链接更多精彩内容