一、对象
1.检测属性是否存在
对象.属性名===undefined true->不存在
对象.hasOwnProperty('属性名') true->存在 false->不存在
'属性名'in 对象 true->存在 false->不存在
练习:创建商品对象,包含的属性有编号,标题,价格;如果产地属性不存在,则添加该属性;如果属性存在,则打八折.
var laptop={
lid:30,
title:'战神电脑',
price:6000
}
//判断不存在
//laptop.madeIn===undefined
if(!laptop.hasOwnProperty('madeIn')){
laptop.madeIn='中国';
}
if('price'in laptop){
laptop.price*=0.8;
}
console.log(laptop);//{lid: 30, title: '战神电脑', price: 4800, madeIn: '中国'}
2.方法
本质上就是一个函数
var person={
play:function(){
this //指向调用方法的对象
}
}
person.play();//调用方法
练习:创建一个圆对象,包含的属性有半径和圆周率,添加两个方法,分别计算圆的周长和面积,并返回结果.
var circle={
r:50,
p:3.14,
Perimeter:function(){
return 2*this.p*this.r;
},
area:function(){
return this.p*this.r*this.r;
}
}
console.log(circle);
console.log(circle.Perimeter());
console.log(circle.a