1.对象的创建
1. new Object(),然后赋值,操作
2. 创建json对象
3. 可以用定义function的形式,定义构造方法
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="js/jquery-2.1.3.min.js"></script>//引入jQuery包
<script type="text/javascript">
$(function(){
//1. 通过Object创建
var user = new Object();
// 赋值,操作,为这个对象添加字段并赋值
user.name ="123";//本来没有的属性,直接就添加
user.age = 22;
user.eat = function(){//方法也可直接添加
console.debug("吃东西...")
}
// 方法调用: 对象.方法名()
user.eat();//有了方法之后就可以调用了
//2. 通过json,使用json赋值对象,只得到了一个对象
var student = {
"name":"123",
"age":19,
"say":function(){//这样添加属性和字段
console.debug("hello!")
}
}
student.say();//想要得到其他的需要再使用json重复写一次
// 3. 通过function定义构造方法
function People(name,age){//相当于一个类,同时创建一个构造方法
this.name = name;
this.age = age;
this.run = function(){//方法的创建
// this 谁调用就指向谁
console.debug(this.name+","+this.age);
}
}
var p = new People("123",21);
var p2 = new People("123",22);
console.debug(p);
console.debug(p2);
p2.run();
console.debug(p2.name);
});
</script>
</head>
<body>
</body>
</html>
2.操作对象,动态添加方法属性
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="js/jquery-2.1.3.min.js"></script>
<script type="text/javascript">
$(function(){
// 通过function定义构造方法
function People(name,age){
this.name = name;
this.age = age;
this.run = function(){
// this 谁调用就指向谁
console.debug(this.name+","+this.age);
}
}
var p = new People("汪汪",21);//创建对象p
p.age = 22;
p.address = "武汉";//添加属性address
p.say = function(){//添加方法
console.debug("sayHello")
}
p.say();//调用方法
// js可以删除一个对象已经定义的属性或方法
delete p.age;
delete p.say;
// p.say(); 删除的方法就不能在调用了 ...
// 方法调用:对象.方法名();属性调用: 对象.属性名;
//动态调用方法: 对象[方法名]();
//动态属性调用: 对象[属性名];
p["run"]();//调用名字为run的方法
console.debug(p["name"])//同样使用名字为name的字段
})
</script>
</head>
<body>
</body>
</html>
3.对象属性遍历
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="js/jquery-2.1.3.min.js"></script>
<script type="text/javascript">
$(function(){
// 通过function定义构造方法
function People(name,age){
this.name = name;
this.age = age;
this.run = function(){
// this 谁调用就指向谁
console.debug(this.name+","+this.age);
}
}
var p = new People("汪汪",21);
//添加属性和方法
p.age = 22;
p.address = "武汉";
//遍历这个对象
for(var i in p){
// 还想知道属性的值,就必须通过动态调用 对象[属性名]
// 如果是方法,想直接运行方法, 就需要判断 ,对象[方法名]()
if("function" == (typeof p[i])){
p[i]();
}else{
console.debug(i,p[i]);
}
}
})
</script>
</head>
<body>
</body>
</html>