JS进阶笔记4

47 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第4天,点击查看活动详情

2.5 JavaScript对象

JavaScript面向对象编程概述:

JavaScript中对象的定义为:无序属性的集合,其中的属性可以是基本值、对象或者函数(ECMA-262)。简单来说,对象就是一组无序的名称/值对。当值为基本值或对象时,这样的名称/值对称为对象的属性及属性值,当值为函数时,这样的名称/值对称为对象的方法。

JavaScript对象的创建:

方法一:调用Object()创建对象

image-20220925174007839

方法二:使用对象字面量,相比方法一,更简洁

image-20220925174103784

方法三:使用构造函数模式:构造函数实质上是具有如下特点的普通函数:

  • 构造函数内通常使用this关键字对属性和方法赋值

  • 通过 new 构造函数名()的形式调用构造函数创建对象

  • 构造函数不需要返回值

  • 注意:构造函数与普通函数无实质区别,普通函数也可以执行 new 普通函数(),只是函数内没有通过this对属性和方法赋值,创建的是空对象,构造函数也可以像普通函数那样被调用

    function Student(num, name, dob, gender) {
        this.num = num;
        this.name = name;
        this.dob = dob,
        this.gender = gender;
        this.getAge = function () {
            let now = new Date();
            let diffInMM = now - this.dob;
            return Math.trunc(diffInMM / (1000 * 60 * 60 * 24 * 365));
        };
        this.toString = function () {
            return `学号:${this.num},姓名:${this.name},年龄:${this.getAge()},性别:${this.gender}`;
        };
    }
    let stu1 = new Student('2018111123', '张华', new Date('2001-10-20'), '女');
    let stu2 = new Student('2018111124', '刘晓', new Date('2001-07-15'), '男');
    console.log(stu1.toString());
    console.log(stu2.toString());
    

    原型(Prototype)

  • 在JavaScript中,每个函数均有一个prototype(原型)属性,其值为一个对象,称为“原型对象”

  • 所有的对象均有一个__proto__(proto前后两个下划线)属性,通过调用new 函数名()创建的对象,其__proto__属性指向该函数的prototype

  • 将属性、方法放置在构造函数的prototype中,可实现所有实例对象共享这些属性和方法

    image-20220925174745440

2.6 原型链和对象的继承

当访问一个对象的某个属性时,会先在这个对象本身属性上查找,如果没有找到,则会去它的__proto__隐式原型上查找,即它的构造函数的prototype,如果还没有找到就会再在构造函数的prototype的__proto__中查找,这样一层一层向上查找就会形成一个链式结构,我们称为原型链。 使用class关键字定义类

  • 现有的基于原型的继承的语法糖

    class Rectangle {
      constructor(height, width) {
        this.height = height;
        this.width = width;
      }
    }
    
  • 不同于函数声明,类声明不会提升,先声明,后访问

    let p = new Rectangle(); // ReferenceError
    class Rectangle {}
    

匿名类

// 匿名类
let Rectangle = class {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
};
console.log(Rectangle.name); // output: "Rectangle"
// 具名类
let Rectangle = class Rectangle2 {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
};
console.log(Rectangle.name); // 输出: "Rectangle2"