當(dāng)前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
JS中对象的总结
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>03_對象</title>
</head>
<body>
<!--
1. 什么是對象?* 代表現(xiàn)實(shí)中的某個(gè)事物, 是該事物在編程中的抽象* 多個(gè)數(shù)據(jù)的集合體(封裝體)* 用于保存多個(gè)數(shù)據(jù)的容器
2. 為什么要用對象?* 便于對多個(gè)數(shù)據(jù)進(jìn)行統(tǒng)一管理
3. 對象的組成* 屬性* 代表現(xiàn)實(shí)事物的狀態(tài)數(shù)據(jù)* 由屬性名和屬性值組成* 屬性名都是字符串類型, 屬性值是任意類型* 方法* 代表現(xiàn)實(shí)事物的行為數(shù)據(jù)* 是特別的屬性==>屬性值是函數(shù)
4. 如何訪問對象內(nèi)部數(shù)據(jù)?* .屬性名: 編碼簡單, 但有時(shí)不能用* ['屬性名']: 編碼麻煩, 但通用
-->
<script type="text/javascript">// 創(chuàng)建對象var p = {name: 'Tom',age: 12,setName: function (name) {this.name = name},setAge: function (age) {this.age = age}}// 訪問對象內(nèi)部數(shù)據(jù)console.log(p.name, p['age'])p.setName('Jack')p['age'](23)console.log(p['name'], p.age)</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>03_相關(guān)問題</title>
</head>
<body>
<!--
問題: 什么時(shí)候必須使用['屬性名']的方式?* 屬性名不是合法的標(biāo)識名* 屬性名不確定
-->
<script type="text/javascript">// 創(chuàng)建對象var p = {}/*情形一: 屬性名不是合法的標(biāo)識名*//*需求: 添加一個(gè)屬性: content-type: text/json */// p.content-type = 'text/json' //不正確p['content-type'] = 'text/json'/*情形二: 屬性名不確定*/var prop = 'xxx'var value = 123// p.prop = value //不正確p[prop] = valueconsole.log(p['content-type'], p[prop])
</script>
</body>
</html>
總結(jié)
- 上一篇: 自己想在外面购买电脑配置组装电脑,但是又
- 下一篇: JS中的回调函数