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