js对象分类

111 阅读2分钟

正方形

* 已知正方形边长,算出面积和周长

let square = {
  width: 5,
  getArea(){
    return this.width * this.width
  },
  getLength(){
    return this.width * 4
  }
}
* 此代码只是用一个正方形

*如果有12个对象怎么办

let squareList = []
for(let i = 0; i < 12; i++){
  squareList[i] = {
    width: 5,
    getArea(){
      return this.width * this.width
    },
    getLength(){
    return this.width * 4
    }
  }
}
* 看 用for循环搞定了

* 那如果width不全是5 怎么办

let squareList = []
let widthList = [5,6,5,6,5,6,5,6,5,6,5,6]
for(let i = 0; i<12; i++){
  squareList[i] = {
    width: widthList[i],
    getArea(){
      return this.width * this.width
    },
    getLength(){
      return this.width * 4
    }
  }
}
*垃圾代码太占内存

* 好办借助原型解决,将12个对象的共有属性放到原型里

let squareList = []
let widthList = [5,6,5,6,5,6,5,6,5,6,5,6]
let squarePrototype = {
  getArea(){ 
    return this.width * this.width 
  },
  getLength(){
    return this.width * 4
  }
}
for(let i = 0; i<12; i++){
  squareList[i] = Object.create(squarePrototype) 
  squareList[i].width = widthList[i]
}

* square太分散,封装一下,抽离到一个函数里,然后再调用这个函数

let squareList = []
let widthList = [5,6,5,6,5,6,5,6,5,6,5,6]
function createSquare(width){ //此函数叫做构造函数
  let obj = Object.create(squarePrototype)
  // 以 squarePrototype 为原型创建空对象
  obj.width = width
  return obj
}
let squarePrototype = {
  getArea(){ 
    return this.width * this.width 
  },
  getLength(){
    return this.width * 4
  }
}
for(let i = 0; i<12; i++){
  squareList[i] = createSquare(widthList[i])
  // 这下创建 square 很简单了吧!
}
  • new X() 自动做了四件事情
  1. 自动创建空对象

  2. 自动为空对象关联原型,原型地址指定为 X.prototype

  3. 自动将空对象作为 this 关键字运行构造函数

  4. 自动 return this

  • 构造函数 X
  1. X 函数本身负责给对象本身添加属性

  2. X.prototype 对象负责保存对象的共用属性

function Square(width){ 

  this.width = width

}

Square.prototype.getArea = function(){ 

  return this.width * this.width 

}

Square.prototype.getLength = function(){

  return this.width * 4

}

let square = new Square(5)

例:

1.png

代码规范

  • 大小写

所有构造函数(专门用于创建对象的函数)首字母大写

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

  • 词性

new 后面的函数,使用名词形式

如 new Person()、new Object()

其他函数,一般使用动词开头

如 createSquare(5)、createElement('div')

代码式例

  • class 6.png
  • function 7.png