js对象分类

本文深入探讨JavaScript对象分类,包括数组对象、函数对象,以及ES6中的class。强调对象分类的重要性,讲解构造函数、原型和new操作符的工作原理,提供代码规范指导,并对比ES6类与原型的区别。
摘要由CSDN通过智能技术生成

js对象分类

其它
1.推荐文章
你可以不会class,但是一定要学会prototype
JS的new到底是干什么的?
JS中proto和prototype存在的意义是什么?
ES6 所有新特性
2.构造函数就是可以构造出对象的函数
3.封装:把细节写到一个函数里,别人只需要调用函数并且传个参数(宽度)
4.函数也是对象
5.js之父为了让new可以运行提前规定:
所有js里的函数自带prototype属性。
prototype属性自带constructor。
constructor的值等于函数本身。
6.共有属性与原型的关系:包含与被包含。
共有属性这整个对象叫做原型。
对象的地址就是原型的地址,里面的每一个属性叫共有属性。
在这里插入图片描述

对象需要分类吗?

需求:输出各种形状的面积和周长

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

来一打正方形

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

width不全是5怎么办?

let squareList=[]
let widthList=[5,6,7,8,5,6,7,5,5,4,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,7,8,9,5,6,7,8,9,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]
}
控制台输入:squareList

在这里插入图片描述

还是垃圾代码,创建的square的代码太分散了。
那就把代码抽离到一个函数里,然后调用函数。
抽离到函数

let squareList=[]
let widthList=[5,6,7,8,9,5,6,7,8,9,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])
  //封装,把细节写到一个函数里,别人只需要调用函数并且传个宽度。
}

squarePrototype原型和createSqua

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

老老老老李

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值