// 对象 数组 函数
var obj = new Object();
var arr = new Array();
var fun = function(){
console.log('我是函数');
};
// 数据类型
console.log(typeof obj); // object
console.log(typeof arr); // object
console.log(typeof fun); // function
console.log(typeof obj == typeof fun); // false
// 这里结果不同,但是 函数同样被认为是对象,同样有属性(局部变量)和方法(内部方法)
console.log('-----------------------------------------');
// 复杂对象
var user = {
name: 'userA',
age: 24,
isVIP:true,
address:["保定理工学院","石家庄桥西区开发路223号",['开发区','临沂市','山东省']], //收货地址,公司位置, 籍贯
payEnabled:function(){ // 是否有充值能力
console.log('payEnabled--\>我很有钱,还花不完!');
return true;
},
pay:function(){ // 充值
// if(payEnabled()){ // 报错 ReferenceError: payEnabled is not defined
if(this.payEnabled()){
// this 在这里指代 user对象
// 即 this.payEnabled() == user.payEnabled()
console.log('pay--\>充值100元!');
}
},
family:{
mother:{
name:'userA_m',
age:42,
children:['userA','userA_b']
},
father:{
name:'userA_f',
age:45,
children:['userA_b','tom']
},
borther:{
name:'userA_b',
age:15
},
isFirstWife:function(){// 是否是重组家庭
var fatherChild = user.family.father.children;
var motherChild = this.mother.children; // 此处 this 指代family对象,而不是user对象
//逻辑:父母的小孩数量相同,名字相同,认定父母是原配夫妻
if(fatherChild.length == motherChild.length){
for(var i = 0; i < fatherChild.length; i++){
if(fatherChild[i] != motherChild[i]){
console.log('isFirstWife --\> 这个家庭是重组家庭!');
return false;
}
}
console.log('这个家庭不是重组家庭!');
return true;
}
console.log('这个家庭是重组家庭!');
return false;
}
}
}
// 关于这里的两处this指向差异的解释:
// this 所在的方法属于谁,this就指代谁;
user.pay(); // 调用 user的pay方法;函数的嵌套(内部调用)
console.log('淘宝收货地址:'+ user.address[0]); // 查找user对象的第一个地址;
console.log('籍贯所属省份:'+ user.address[2][2]); // 查找user对象的籍贯地址;
console.log("是否重组家庭:" + (user.family.isFirstWife()?'否':'是')); // 这是个重组家庭吗?
js 复杂对象
最新推荐文章于 2023-06-14 17:29:12 发布