输出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
}
}
}
——————————————————————————————
输出不同边长正方形的面积和周长 缺点:太浪费内存
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
}
}
}
——————————————————————————————
借助原型
let squareList =[]
let widthList = [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]
}
缺点:squareList太分散
——————————————————————————————
改进
let squareList =[]
let widthList =[5,6,5,6,5,6,5,6,5,6]
function createSquare(width) //此函数叫做构造函数
let obj =Object.create(squarePrototype)
obj.width =width
return obj
}
let squarePrototype ={
getArea(){
return this.wdith *this.width
},
getLength(){
return this.width *4
}
}
for(let i= 0; i<12; i++){
squareList[i] =createSquare(widthList[i])
//这下创建squareList很简单了吧。
}
—————————————————————————————— 函数和原型结合
let squareList =[]
let widthList =[5,6,5,6,5,6,5,6,5,6]
function createSquare(width){
let obj =Object.create(createSquare.squarePrototype) //先使用后定义?NO
obj.width =width
return obj
}
createSquare.squarePrototype ={
//把原型放在函数上,结合够紧密了吗?
getArea(){
return this.width *this.width
},
getLength(){
return this.width *4
},
constructor :createSquare //方便通过原型找到构造函数
}
for(let i=0;i<12;i++){
squareList[i] =createSquare(widthList[i])
console.log(squareList[i].constructor)
// constructor 可以知道谁构造了这个对象:你妈是谁?
}
这段代码几乎完美
函数和原型结合(重写)
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(let i =0; i<12; i++){
squareList[i] =new Square(widthList[i])
console.log(squareList[i].constructor)
}
//多美,几乎没有一句多余的废话
//每个函数都有prototype属性,这是JS之父故意的
//每个prototype都有constructor属性,也是故意的
总结
- 自动创建空对象
- 自动为空对象关联原型,原型地址指定为X.prototype
- 自动将空对象作为this关键字运行构建函数
- 自动return this
- 这就是 JS之父的爱
构造函数X
- X函数本身负责给对象本身添加属性
- X.prototype对象负责保存对象的共用属性