对class不理解地方的整理

JavaScript 类实质上是 JavaScript 现有的基于原型的继承的语法糖。类语法不会为JavaScript引入新的面向对象的继承模型。

一、定义类:

类实际上是个“特殊的函数”,类语法有两个组成部分:类表达式(类声明)和类声明。

1.类声明
要声明一个类,使用带有class关键字的类名(此处类名是:Rectangle )。

class Rectangle {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
}

提升问题:函数声明和类声明之间的一个重要区别是函数声明会提升,类声明不会。需要声明类,然后访问它,否则会抛出一个ReferenceError:

let p = new Rectangle(); 
// ReferenceError
class Rectangle {}

2.类表达式
类表达式可以是被命名的或匿名的。

/* 匿名类 */ 
let Rectangle = class {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
};

/* 命名的类 */ 
let Rectangle = class Rectangle {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
};

二、构造函数和方法

1.构造函数
constructor方法用于创建和初始化一个由class创建的对象。一个类只能有一个 “constructor”方法。

一个构造函数可以使用 super 关键字来调用一个父类的构造函数。

2.原型方法

class Rectangle {
    // constructor
    constructor(height, width) {
        this.height = height;
        this.width = width;
    }
    // Getter
    get area() {
        return this.calcArea()
    }
    // Method
    calcArea() {
        return this.height * this.width;
    }
}
const square = new Rectangle(10, 10);

console.log(square.area);   // 100

3.静态方法
static 关键字用来定义一个类的一个静态方法,调用静态方法不需要实例化该类,但不能通过一个类实例调用静态方法。静态方法通常用于为一个应用程序创建工具函数。

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;
    // console.log(dx, dy);//-5 -5
    return Math.hypot(dx, dy); //对于给定的直角三角形的两个直角边,求其斜边
  }
}

const p1 = new Point(5, 5);
const p2 = new Point(10, 10);
// console.log(p1);//Point { x: 5, y: 5 }
console.log(Point.distance(p1, p2)); //7.0710678118654755

4.实例属性:
实例的属性必须定义在类的方法里:

class Rectangle {
  constructor(height, width) {    
    this.height = height;
    this.width = width;
  }
}

静态的或原型的数据属性必须定义在类定义的外面。

Rectangle.staticWidth = 20;
Rectangle.prototype.prototypeWidth = 25;
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值