带你读《现代Javascript高级教程》十三、面向对象编程与Class(2)

简介: 带你读《现代Javascript高级教程》十三、面向对象编程与Class(2)

带你读《现代Javascript高级教程》十三、面向对象编程与Class(1)https://developer.aliyun.com/article/1349609?groupCode=tech_library


3) 方法

在Class中定义的函数称为方法。可以直接在Class的内部定义方法,也可以使用ES6的简写形式。

 

class Rectangle {
  constructor(width, height) {
    this.width = width;
    this.height = height;
  }
  area() {            // 定义方法
    return this.width * this.height;
  }
  perimeter() {
    return 2 * (this.width + this.height);
  }}

4 方法的访问修饰符

在Class中,可以使用访问修饰符来限制方法的访问权限。ES6中的Class默认所有方法都是公共的,可以被外部调用。但我们可以使用static、get、set、privateprotected等修饰符来控制方法的访问。

 

  • static:定义静态方法,只能通过类本身调用,不能通过类的实例调用。
  • get和set:定义属性的读取和设置方法,使用类似访问属性的语法进行调用。
  • private:定义私有方法,只能在类的内部被访问,外部无法访问。
  • protected:定义受保护方法,只能在类的内部和子类中被访问,外部无法访问。
class Rectangle {
  static description = 'This is a rectangle';  // 静态属性
  constructor(width, height) {
    this.width = width;
    this.height = height;
  }
  static createSquare(side) {     // 静态方法
    return new Rectangle(side, side);
  }
  get area() {           // Getter方法
    return this.width * this.height;
  }
  set area(value) {     // Setter方法
    this.width = Math.sqrt(value);
    this.height = Math.sqrt(value);
  }
  privateMethod() {    // 私有方法
    console.log('This is a private method');
  }
  protectedMethod() {   // 受保护方法
    console.log('This is a protected method');
  }
  publicMethod() {      // 公共方法
    console.log('This is a public method');
    this.privateMethod();
    this.protectedMethod();
  }}

 

在上述示例中,我们定义了一个Square类,它继承自Rectangle类。通过super关键字调用父类的构造函数,确保父类的属性被正确初始化。子类可以新增或覆盖父类的方法。

 

const square = new Square(5);
console.log(square.area());       // 输出:25
console.log(square.perimeter());  // 输出:20

4. 类的静态方法和属性

静态方法和属性属于类本身,而不是类的实例。静态方法和属性可以通过类名直接访问,无需实例化类。

 

class MathUtil {
  static PI = 3.14159;    // 静态属性
  static square(number) {    // 静态方法
    return number * number;
  }}

 

在上述示例中,我们定义了一个MathUtil类,它具有一个静态属性PI和一个静态方法square()。可以通过类名直接访问静态属性和方法。

 

console.log(MathUtil.PI);        // 输出:3.14159
console.log(MathUtil.square(5)); // 输出:25


带你读《现代Javascript高级教程》十三、面向对象编程与Class(3)https://developer.aliyun.com/article/1349607?groupCode=tech_library

相关文章
|
9天前
|
Web App开发 JavaScript 前端开发
JavaScript 类(class)
JavaScript 类(class)
14 2
JavaScript 类(class)
|
3月前
|
JavaScript
vue中使用 HotKeys.js 教程(按键响应、快捷键开发)
vue中使用 HotKeys.js 教程(按键响应、快捷键开发)
149 0
|
7天前
|
JavaScript 前端开发
js之class继承|27
js之class继承|27
|
7天前
|
JavaScript 前端开发 Java
js面向对象编程|24
js面向对象编程|24
|
2月前
|
JavaScript NoSQL 前端开发
|
3月前
|
JSON JavaScript 数据格式
vue 绘制波形图 wavesurfer.js (音频/视频) 【实用教程】
vue 绘制波形图 wavesurfer.js (音频/视频) 【实用教程】
303 3
|
3月前
|
JavaScript
JS 自测题 —— 手写 class
JS 自测题 —— 手写 class
20 0
|
3月前
|
JavaScript
vue 农历日期转公历日期(含插件 js-calendar-converter 使用教程)
vue 农历日期转公历日期(含插件 js-calendar-converter 使用教程)
182 0
|
3月前
|
开发框架 监控 JavaScript
企业级node.js开发框架 【egg.js】 实用教程
企业级node.js开发框架 【egg.js】 实用教程
40 0
|
3月前
命令行加载特效 【cli-spinner.js】 实用教程
命令行加载特效 【cli-spinner.js】 实用教程
26 0
下一篇
无影云桌面