12.1 通过原型来节省公有函数的内存
原本的写法
let squareList = []
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
},
constructor: createSquare //能让实例找到妈
}
for(let i= 0;i<12;i++){
squareList[i] = createSquare(widthList[i])
console.log(squareList[i].constructor())//实例找到妈
}
js优化后的写法:
let squareList = []
let widthList = [5, 6, 5, 6,5, 6,5, 6,5, 6,5, 6]
//1. 创建空对象
function Square(width) {
this.width = width
}
//2. 指定原型
Square.prototype.getArea = function () {
return this.width * this.width
}
Square.prototype.getLength = function () {
return this.width * 4
}
for(let i= 0;i<12;i++){
//3.实例对象
squareList[i] = new Square(widthList[i])
console.log(squareList[i].constructor())//实例找到妈
}
写类的时候需要注意的:
- 构造函数首字母大写
- 实例小写
- 其他函数动词开头
如何知道,构造函数需要传几个参数?
-
js无法解决, 需要查文档
-
看源码
如何查看一个对象的原型
原型公式, 通过查看构造函数的prototype来查看原型
空对象的内存图:
Object 构造函数是什么的, 原型是什么? .
Object 的构造函数是Function, 而Function的prototype 也是#309
Function.prototype == Object.__proto__ //true
window.Function由自己构造, 浏览器构造了Function, Function构造了自己
window是谁构造出来的
小window由大Window构造, 通过constructor可以查看
12.2 函数的分类
Array常见的原型
-
pop弹最后面的元素,
-
shift弹最前面的元素. 都要删除
-
concat 连接两个数组
-
join将数组所有元素连接成一个字符串
arr2 = [1, 2, 3, 4] arr2.join('方') //"1方2方3方4"
Array的两层__proto__
第一层: Array的原型
第二层: Array中元素的原型
###12.3 原型和class
ES6的class
推荐用class