对象是一组无序的相关属性和方法的集合
- 自定义对象
- 内置对象(Math、Date、String、Number、Function、Array、RegExp)
- 浏览器对象(DOM)
对象创建
```javascript // 对象字面量创建对象 const obj1 = { name: ‘沐颖汐’, sex: ‘男’, age: 18, sayHi: function () { console.log(‘我的名字是:’ + this.name); } };
// new Object创建对象 const obj2 = new Object();
<a name="gxG33"></a>
### ES6简化对象
```javascript
let name = '名字'
let age = 18
let eat = function (food) {
console.log('吃' + food)
}
/*
* const obj = {
* name: name,
* age: age,
* eat: eat,
* say: function () {}
* }
*/
const obj = {
name,
age,
eat,
say() {}
}
获取对象属性和方法
const obj = {
name: '沐颖汐',
sex: '男',
age: 18,
sayHi: function () {
console.log('我的名字是:' + this.name);
}
};
console.log(obj.name); // 沐颖汐
console.log(obj['age']); // 18
obj.sayHi(); // 我的名字是:沐颖汐
对象遍历
const obj = {
name: '沐颖汐',
sex: '男',
age: 18,
sayHi: function () {
console.log('我的名字是:' + this.name);
}
};
for (let key in obj) {
console.log(key + ':' + obj[key]);
}
/*
* name:沐颖汐
* sex:男
* age:18
* sayHi:function () {
* console.log('我的名字是:' + this.name);
* }
*/
添加属性和方法
const obj = new Object();
obj.name = '沐颖汐';
obj.age = 18;
obj.sex = '男';
obj.sayHi = function () {
console.log('我的名字是:' + this.name);
}
构造函数创建对象
// 构造函数创建对象
function People(name, sex) {
this.name = name;
this.sex = sex;
this.sayHi = function () {
console.log('我的名字是:' + this.name);
}
}
const yingximu = new People('沐颖汐', '男');
console.log(yingximu.name); // 沐颖汐
yingximu.sayHi(); // 我的名字是:沐颖汐
console.log(yingximu.age); // undefined
yingximu.age = 18;
console.log(yingximu.age); // 18