JS 对象分类
这两天在学习数组,把对象分类的笔记总结给忘了(实际上就是数组学的不太理想,需要转换一下思维),那我今天就来给它补上吧!
构造函数
构造函数 ,是一种特殊的方法。主要用来在创建对象时初始化对象, 即为对象成员变量赋初始值,总与new运算符一起使用在创建对象的语句中。
注:每个函数都有prototype属性,每个prototype都有constructor属性
new()起到的作用:
1、自动创建空对象
2、自动为空对象关联原型,原型地址指定为x.prototype
3、自动将空对象作为this关键字运行构造函数
4、自动return this
构造函数X
X函数本身负责给对象添加属性
X.prototype对象负责保存对象的公用属性
例题:画出十二个边长为5,6的正方形,并求面积和周长
let squareList=[]
let widthList=[5,6,5,6,5,6,5,6,5,6,5,6,5]
function Square (width){ //Squery构造的函数
this.width=width
}
Square.prototype.getArea=function(){
return this.width*this.width
}
Square.prototype.getLength=function(){
return this*4
}
let square = new Square(5)
for (let i=0; i<12;i++){
squareList[i] = new Square(widthList[i]) // 每遍历一次拿widthList的一个数
console.log (squareList[i].constructor) // constructor 查看谁构造了这个对象
}
注意:用this就不能用箭头函数
代码规范
1、所有构造函数(专门用于创建对象的函数)首字母大写
2、所有被创建出来的对象首字母小写
3、new后面的函数用名词形式,例:new person()、new boject()
4、其他函数一般使用动词开头
原型公式(仅此一家):
对象.__proto__===其构造函数.prototype
例:
let square = new Square
// square的原型:Square.prototype
类
类是针对于对象的分类,有无数种,常见的有Arry、Function、Data、RegExp等。
数组类(数组对象)
定义一个数组:
let arr = [1,2,3]
let arr = new Array(1,2,3) //元素为1,2,3
let arr = new Array(3) //长度length为3
数组对象的自身属性
'0'/'1'/'2'/'length'
数组对象的共用属性
'push' 'pop' 'shift' 'unshift' 'join'
注意:属性名只有字符串
函数类(函数对象)
定义一个函数
function fn(x,y){return x+y}
let fn2= function fn(x,y) {return x+y}
let fn = (x,y)=>x+y
let fn=new Function ('x','y','return x+y')
函数对象的自身属性:'name' 'length'
共用属性:'call' 'apply' 'bind'
注:所有函数都是有由window.Function构造的,包括Object和Window
class类
新语法,只简单的举个例子:
class Square{
constructor (width){
this.width=width
}
getArea(){
return this.width*width
}
}
网友评论