三种声明方式
2025年4月30日大约 1 分钟
第一种
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>声明对象</title>
</head>
<body>
<script type="text/javascript">
//第一种声明方式使用方式
var obj=new Object;
//添加属性
obj.name="龙哥";
obj.age="18";
//动态添加属性
var bie="sex";
obj[bie]="男";
//添加方法
obj.eat=function(food)
{
document.write('龙哥正在吃....'+food);
}
obj.eat('烤乳猪');
console.log(obj);
console.log(typeof(obj));
//删除
delete(obj.sex);
console.log(obj);
console.log(typeof(obj));
//修改
obj.name="双哥";
console.log(obj);
console.log(typeof(obj));
//查询
console.log(obj.eat);
</script>
</body>
</html>
第二种
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>对象声明2</title>
</head>
<body>
<script type="text/javascript">
//声明时别忘了带等号, 最后一个可以不带逗号,其余必须要带逗号
var bird=
{
name: "大雁",
chicun: "大型",
fheight: "万米",
fly:function()
{
document.write(this.name+"正在天空飞...");
},
eat:function()
{
document.write(this.name+"正在捕食");
}
}
bird.fly();
bird.eat();
console.log(bird);
//添加属性
bird.color="灰色";
console.log(bird);
</script>
</body>
</html>
第三种
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>对象声明3</title>
</head>
<body>
<script type="text/javascript">
//第三种形式 构造函数
function Plan(name,size,speed)
{
this.name=name;
this.size=size;
this.speed=speed;
this.fly=function()
{
document.write(this.name+"正在天空飘啊飘!!!!");
}
}
document.write("<br/>");
var apache=new Plan("阿帕奇","中型","中速");
apache.fly();
console.log(apache);
//遍历对象
for(var a in apache)
{
document.write(a+"<==>"+apache[a]+"<br/>");
}
//简便操作
with(apache)
{
document.write(name+" "+size+" "+speed+" "+"<br/>");
}
</script>
</body>
</html>