mirror of
https://github.com/qianguyihao/Web.git
synced 2024-11-01 21:44:45 +08:00
98 lines
1.7 KiB
Markdown
98 lines
1.7 KiB
Markdown
|
|
||
|
|
||
|
|
||
|
## 创建对象的几种方式
|
||
|
|
||
|
### 通过Object
|
||
|
|
||
|
```html
|
||
|
<!DOCTYPE html>
|
||
|
<html lang="en">
|
||
|
<head>
|
||
|
<meta charset="UTF-8">
|
||
|
<title>01_Object构造函数模式</title>
|
||
|
</head>
|
||
|
<body>
|
||
|
<!--
|
||
|
方式一: Object构造函数模式
|
||
|
* 套路: 先创建空Object对象, 再动态添加属性/方法
|
||
|
* 适用场景: 起始时不确定对象内部数据
|
||
|
* 问题: 语句太多
|
||
|
-->
|
||
|
<script type="text/javascript">
|
||
|
/*
|
||
|
一个人: name:"Tom", age: 12
|
||
|
*/
|
||
|
// 先创建空Object对象
|
||
|
var p = new Object()
|
||
|
p = {} //此时内部数据是不确定的
|
||
|
// 再动态添加属性/方法
|
||
|
p.name = 'Tom'
|
||
|
p.age = 12
|
||
|
p.setName = function (name) {
|
||
|
this.name = name
|
||
|
}
|
||
|
|
||
|
//测试
|
||
|
console.log(p.name, p.age)
|
||
|
p.setName('Bob')
|
||
|
console.log(p.name, p.age)
|
||
|
|
||
|
|
||
|
</script>
|
||
|
</body>
|
||
|
</html>
|
||
|
|
||
|
```
|
||
|
|
||
|
|
||
|
### 方式二:对象字面量
|
||
|
|
||
|
```html
|
||
|
<!DOCTYPE html>
|
||
|
<html lang="en">
|
||
|
<head>
|
||
|
<meta charset="UTF-8">
|
||
|
<title>02_对象字面量</title>
|
||
|
</head>
|
||
|
<body>
|
||
|
<!--
|
||
|
方式二: 对象字面量模式
|
||
|
* 套路: 使用{}创建对象, 同时指定属性/方法
|
||
|
* 适用场景: 起始时对象内部数据是确定的
|
||
|
* 问题: 如果创建多个对象, 有重复代码
|
||
|
-->
|
||
|
<script type="text/javascript">
|
||
|
var p = {
|
||
|
name: 'Tom',
|
||
|
age: 12,
|
||
|
setName: function (name) {
|
||
|
this.name = name
|
||
|
}
|
||
|
}
|
||
|
|
||
|
//测试
|
||
|
console.log(p.name, p.age)
|
||
|
p.setName('JACK')
|
||
|
console.log(p.name, p.age)
|
||
|
|
||
|
var p2 = { //如果创建多个对象代码很重复
|
||
|
name: 'Bob',
|
||
|
age: 13,
|
||
|
setName: function (name) {
|
||
|
this.name = name
|
||
|
}
|
||
|
}
|
||
|
|
||
|
</script>
|
||
|
</body>
|
||
|
</html>
|
||
|
```
|
||
|
|
||
|
|
||
|
|
||
|
|
||
|
|
||
|
### 方式三:
|
||
|
|