JS声明对象的语法
通过new Object()直接创建对象
var person =new Object();
// 给对象添加属性并赋值
person.name="张明";
person.age=10;
person.foods=["苹果","橘子","香蕉","葡萄"];
// 给对象添加功能函数
person.eat= function (){
console.log(this.age+"岁的"+this.name+"喜欢吃:")for(var i = 0;i<this.foods.length;i++){
console.log(this.foods[i])
}
}
//获得对象属性值
console.log(person.name)
console.log(person.age)
//调用对象方法
person.eat();
效果:
通过 {}形式创建对象
语法为 var person ={“属性名”:“属性值”,“属性名”,“属性值”,“函数名”:函数}
代码
var person ={
"name":"张小明",
"age":10,
"foods":["苹果","香蕉","橘子","葡萄"],
"eat":function (){
console.log(this.age+"岁的"+this.name+"喜欢吃:")
for(var i = 0;i<this.foods.length;i++){
console.log(this.foods[i])
}
}
}
//获得对象属性值
console.log(person.name)
console.log(person.age)
//调用对象方法
person.eat();
效果: