Day02-原型模式

41 阅读1分钟

先讲一下上一章 构造器模式 缺点

    // 构造器模式代码缺点
    // 由下列代码,发现 getInfo 是不变的,但是每次 new 的时候都会在内存中开辟一个新的地址存储,这样比较浪费不必要的内存
    function createObj(name, age) {
      this.name = name;
      this.age = age;
      this.getInfo = function () {
        console.log(`我叫${this.name},今年${this.age}岁`);
      };
    }

    const ming = new createObj("小明", 18);
    const mei = new createObj("小美", 19);
    ming.getInfo();
    mei.getInfo();

使用 原型模式 优化

    // 使用 原型模式 修改
    // 这样在 new 之后的每个实例上都有一个 getInfo 方法。
    // 同时,这个方法存在原型上,虽然在内存中是一个地址,但是内部的 this 是单独指向每个实例
    // 这样最终就形成了由 构造器模式 + 原型模式 优化后的代码
    function createObj2(name, age) {
      this.name = name;
      this.age = age;
    }
    createObj2.prototype.getInfo = function () {
      console.log(`我叫${this.name},今年${this.age}岁`);
    };

    const mu = new createObj2("小木", 18);
    const lin = new createObj2("小林", 19);
    mu.getInfo();
    lin.getInfo();

使用 ES6 class 实现

    // ES 的方法 class 构造器+原型
    // 以下方法由ES6 的 class 完成。
    // 注意:在 class 类中,内部方法 getInfo 其实是挂载在 实例中的 prototype 上的。
    // 由此可见,class 是由 构造器+原型 俩个模式的合并
    class studentObj {
      constructor(name, age) {
        this.name = name;
        this.age = age;
      }
      getInfo() {
        console.log(`我叫${this.name},今年${this.age}岁`);
      }
    }
    const s1 = new studentObj("小火", 22);
    const s2 = new studentObj("小炎", 21);
    console.log(s1, s2);
    s1.getInfo();
    s2.getInfo();

注意:在 class 类中,内部方法 getInfo 其实是挂载在 实例中的 prototype 上的。