对象是一组无序的相关属性和方法的集合

  • 自定义对象
  • 内置对象(MathDateStringNumberFunctionArrayRegExp)
  • 浏览器对象(DOM)

    对象创建

    ```javascript // 对象字面量创建对象 const obj1 = { name: ‘沐颖汐’, sex: ‘男’, age: 18, sayHi: function () { console.log(‘我的名字是:’ + this.name); } };

// new Object创建对象 const obj2 = new Object();

  1. <a name="gxG33"></a>
  2. ### ES6简化对象
  3. ```javascript
  4. let name = '名字'
  5. let age = 18
  6. let eat = function (food) {
  7. console.log('吃' + food)
  8. }
  9. /*
  10. * const obj = {
  11. * name: name,
  12. * age: age,
  13. * eat: eat,
  14. * say: function () {}
  15. * }
  16. */
  17. const obj = {
  18. name,
  19. age,
  20. eat,
  21. say() {}
  22. }

获取对象属性和方法

  1. const obj = {
  2. name: '沐颖汐',
  3. sex: '男',
  4. age: 18,
  5. sayHi: function () {
  6. console.log('我的名字是:' + this.name);
  7. }
  8. };
  9. console.log(obj.name); // 沐颖汐
  10. console.log(obj['age']); // 18
  11. obj.sayHi(); // 我的名字是:沐颖汐

对象遍历

  1. const obj = {
  2. name: '沐颖汐',
  3. sex: '男',
  4. age: 18,
  5. sayHi: function () {
  6. console.log('我的名字是:' + this.name);
  7. }
  8. };
  9. for (let key in obj) {
  10. console.log(key + ':' + obj[key]);
  11. }
  12. /*
  13. * name:沐颖汐
  14. * sex:男
  15. * age:18
  16. * sayHi:function () {
  17. * console.log('我的名字是:' + this.name);
  18. * }
  19. */

添加属性和方法

  1. const obj = new Object();
  2. obj.name = '沐颖汐';
  3. obj.age = 18;
  4. obj.sex = '男';
  5. obj.sayHi = function () {
  6. console.log('我的名字是:' + this.name);
  7. }

构造函数创建对象

  1. // 构造函数创建对象
  2. function People(name, sex) {
  3. this.name = name;
  4. this.sex = sex;
  5. this.sayHi = function () {
  6. console.log('我的名字是:' + this.name);
  7. }
  8. }
  9. const yingximu = new People('沐颖汐', '男');
  10. console.log(yingximu.name); // 沐颖汐
  11. yingximu.sayHi(); // 我的名字是:沐颖汐
  12. console.log(yingximu.age); // undefined
  13. yingximu.age = 18;
  14. console.log(yingximu.age); // 18