一、对象
1. 什么是对象?
* 多个数据的封装体
* 用来保存多个数据的容器
* 一个对象代表现实中的一个事物
2. 为什么要用对象?
* 统一管理多个数据
3. 对象的组成
* 属性:属性名(字符串)和属性值(任意类型)组成
* 方法:一种特殊的属性(属性值是函数)
4. 如何访问对象内部数据?
* .属性名:编码简单,有时不能用
* ["属性名"]:编码麻烦,能通用
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>03_对象</title>
</head>
<body>
<script type="text/javascript">
var p ={
name:"Tom",
age:12,
setName:function (name) {
this.name = name;
},
setAge:function (age) {
this.age = age;
},
setPrint:function () {
return typeof (this.name);
}
};
p.setName("Bob");
p["setAge"](23);
console.log(p.name,p["age"],p.setPrint()); // Bob 23 String
</script>
</body>
</html>
二、相关问题
问题: 什么时候必须使用['属性名']的方式?
* 属性名包含特殊字符: 1、- 2、 空格
* 属性名(用变量保存)不确定
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>03_相关问题</title>
</head>
<body>
<script type="text/javascript">
var p = {};
//1. 给p对象添加一个属性: content type: text/json
// p.content-type = "text/json"; //不能用
p["content-type"] = "text/json";
console.log(p["content-type"]);
//2. 属性名(用变量存)不确定
var propName = "myAge";
var value = 18;
// p.propName = value; //不能用
p[propName] = value;
console.log(p[propName]);
</script>
</body>
</html>