Js 的对象分类

75 阅读2分钟

构造函数

this:(暂时理解错误的意思)目前你可以认为 this 指的是当前对象

用code 来算正方形

let squart ={
    width:5,
    getArea(){
      return this.width * this.width
    },
    getLength(){
        return this.width * 4 
    }
}
  • 分析得出正方形拥有三个属性:边长、面积、周长

Q:如果有十二个正方形呢?

A: 用for 循环

let squartList = []
for(let i = 0; i<12; i++){
    squartList[i] = {
        width:5,
    getArea(){
       return this.width * this.width
      },
    getLength(){
        return this.width * 4 
    },
  }
}

Q:如果width 是一个五一个 六呢

A: 可以用数组

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

但这样太浪费内存了

截屏2022-03-27 15.07.17.png

let squartList = []
let widthList = [5,6,5,6,5,6,5,6,5,6,5,6]
let squartPrototype ={ 
   getArea(){
      return this.width * this.width
   }
   getLength(){
     return this.width * 4
   }
}
for(let i =0;i<12;i++){
    squartList[i] = Object.create(squarePrototype)
    squartList[i].width = widthList[i]
}
//通过设置一个原型,原型上有共有属性,这样我们只要创建新的对象指定它的共有属性,它就拥有了共有属性,然后你有特有属性 自己再加就完事了

构造函数就是可以构造出一个函数

function createdSquare(width){
    let obj = Object.create(squarePrototype)
    // 以 squarePrototype 为原型创建对象
    obj.width = width
    return obj
}

这个就是 构造函数

let squartList = []
let widthList = [5,6,5,6,5,6,5,6,5,6,5,6]
function createSquare(width){
    let obj = Object.create(createSquare.squarePrototype) 
    obj.width = width
    return obj
}
createSquare.squarePrototype{
    getArea(){
      return this.width * this.width
   }
   getLength(){
     return this.width * 4
   }
   constructro:createSquare // 方便通过原型构造函数
}
for(let i =0;i<12;i++){
    squareList[i] = createSquare(widthList[i])
    console.log(squareList[i].cosntructor)
    // cosntructor 可以知道谁构造了这个对象 
}

Q:let obj = Object.create(createSquare.squarePrototype) 这句啥时候执行

A:会调用createSquare 才会执行,先写到这里没有执行 ,所以是可以先放到这里什么时候 createSquare 在最后一行 执行,这句执行完之后 才会进去,在执行 createSquare.squarePrototype 我早就定义好了

如果使用 new

let squareList = []
let widthList = [5,6,5,6,5,6,5,6,5,6,5,6]
function Square(width){ // 声明一个函数
    this.width = width
}
Square.prototype.getArea = function(){
    return this.width * this.width
}
Square.prototype.getLength = function(){
    return this.width * 4
}
for(lei i =0;i<12;i++){
 squareList[i] = new Square(widthList[i])
 console.log(squareList[i].constructro)
}

使用了new之后会自动做了四件事情:

  • 自动创建空对象

  • 自动把空对象的原型关联为X的任何一个函数的prototype

  • 然后它会把空对象作为this, 来运行这个函数

  • 然后自动帮你 return this -- 这就是来自JS之父的❤️

构造函数的X 是指 有两部分:

  1. 它的函数自身,这个自身里用来添加新对象的自身属性

  2. prototype 是用来添加新对象的共有属性