js的对象以及创建对象的方式
- 输出一个对象的所有属性名和各属性的值。
var dog = {
name : 'wangcai',
height:1.25,
age :12,
friends:['xiaohei','xiongxiong']
}
for(var pname in dog){
console.log(pname,dog[pname]);
}
或者
console.log(dog.name,dog.height,dog.age,dog.friends);
- 对象调用它的方法。
var dog = {
name : 'wangcai',
height:1.25,
age :12,
friends:['xiaohei','xiongxiong'],
run:function(){
console.log(this.name + '在操场上跑步');
},
eat:function(meat){
console.log(this.name + '吃' + meat);
}
};
dog.run();
dog.eat('五花肉');
*通过构造方法生成对象
function Dog(){
console.log('----------');
}
console.log(typeof Dog());//会输出undefined
var dog1 = new Dog();//新建了一个对象
var Dog = function(){
this.name = null;
this.height = null;
this.age = null;
this.eat = function(){
console.log('吃');
};
this.run = function(){
console.log('跑');
}
}
var dog1 = new Dog();
dog1.name = 'wangcai';//给新建的对象里面的属性赋值
var dog2 = new Dog();
dog2.name = 'xiaohei';//给新建的对象里面的属性赋值
}
var Dog = function(name,height,age){
this.name = name;
this.height = height;
this.age = age;
this.eat = function(meat){
console.log(this.name + '吃' + meat);
};
this.run = function(){
console.log(this.name + '跑');
}
};
var dog1 = new Dog('wangcai',1.23,10);
var dog2 = new Dog('ahuang',0.11);
console.log(dog1,dog2);//dog2的age输出为undefined。
- && 和 ||
var name1 = 'name1';
var name2 = 'name2';
var name3 = 'name3';
var name4 = 'name4';
var newName = null;
if(name1){
newName = name1;
}else if(name2){
newName = name2;
}else if(name3){
newName = name3;}
else{
newName = name4;
}
console.log(newName);
newName = name1 || name2 || name3 || name4;//从左往右只要一个有值就停止并赋值给newName;
console.log(newName);
var age =22;
if(age > 20){
console.log('可以结婚了!');
}
(age > 20)&& console.log('可以结婚了!');//输出可以结婚了,左边满足条件就执行右边。