JavaScript 对象分类

241 阅读2分钟

对象需要分类

理由1. 有很多对象拥有一样的属性和行为,需要把它们分为同一类,如 square1 和 square2,这样创建类似对象的时候就很方便。

理由2. 还有很多对象拥有其他的属性和行为,所以就需要不同的分类,比如 Square / Circle / Rect 就是不同的分类,Array / Function 也是不同的分类,而 Object 创建出来的对象,是最没有特点的对象。

类型 V.S. 类

类型是 JS 数据的分类,有七种:number / string / bool / symbol / null / undefined / object

类是针对于对象的分类,有无数种,常见的有数组 Array / Function / Date 等。

定义类的两种方式

1. 使用构造函数(结合原型)

构造函数是一种专门用于创建对象的函数。首先创建构造函数,在其内部用this关键字指代实例对象。

function Square(width) {
  this.width = width 
}

将共有属性定义在构造函数的prototype对象之上。

Square.prototype.getArea = function() {
  return this.width * this.width
}
Square.prototype.getLength = function() {
  return this.width * 4
}

使用new生成实例对象。

let square1 = new Square(5)
square1.getArea()   //25
square1.getLength() //20

在 JS 中,所有函数在被定义时就拥有prototype属性,且在prototype中默认有constructor属性,值为函数本身。

构造函数 X

  • X 函数本身负责给对象自身添加属性
  • X.prototype对象负责保存对象的共用属性

new 运算符

new运算符创建一个用户定义的对象类型的实例或具有构造函数的内置对象的实例。

new X()自动做了四件事:

  1. 自动创建一个空对象
  2. 自动为对象关联原型,原型的地址指定为X.prototype
  3. 自动将空对象作为this关键字运行构造函数
  4. 自动return this

代码规范

关于大小写:

  • 所有构造函数首字母大写
  • 所有被构造出来的对象,首字母小写

关于词性:

  • new 后面的函数,使用名词形式,如 new Person()、new Object()
  • 其他函数,一般使用动词开头,如 createSquare(5)、createElement('div')

2. 使用 class

class Square{
  //使用 constructor 方法添加属性
  constructor(width){
    this.width = width
  } 
  getArea(){ 
    return this.width * this.width 
  }
  getLength(){
    return this.width * 4
  }
}
let square1 = new Square(5)
square1.getArea()   //25
square1.getLength() //20

constructor是一个构造方法,用于创建和初始化一个由class创建的对象。一个类只能有一个名为 “constructor” 的特殊方法。