Day01 - 构造器模式

68 阅读2分钟

在记录之前先问一个问题,r1 和 r2 分别打印什么?答案在最后

    function MyFunction() {
      this.name = "123";
      return [4, 5, 6];
    }
    function MyFunction2() {
      this.name = "123";
      return "456";
    }

    const r1 = new MyFunction();
    const r2 = new MyFunction2();
    console.log(r1, r2);

举例:学生入学,创建学生信息。

1. 普通创建同学 - 每个同学结构一样,创建信息时重复劳动过多

    const studentOne = { name: "同学1", age: 15 };
    const studentTwo = { name: "同学2", age: 16 };

2. 构造器模式 - 可以省略重复结构,只需要个人的具体信息

    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();

在学习 构造器 的时候突然发现一个 之前漏掉或忘记的知识点

问 r1 和 r2 分别打印什么?

    function MyFunction() {
      this.name = "123";
      return [4, 5, 6];
    }
    function MyFunction2() {
      this.name = "123";
      return "456";
    }

    const r1 = new MyFunction();
    const r2 = new MyFunction2();
    console.log(r1, r2);
    // r1: [ 4, 5, 6 ]
    // r2: { name: '123' }

至于为什么 则需要研究一下 new 做了什么事情?

    1. 创建一个空的简单 JavaScript 对象(即 {} );
    2. 为步骤 1 新创建的对象添加属性  `__proto__` ,将该属性链接至构造函数的原型对象;
    3. 将步骤 1 新创建的对象作为 `this` 的上下文;
    4. 如果 `构造函数` 没有返回引用类型,则返回 `this`,否则返回 引用类型
    
    // 咱们自己写一个 仿 new 函数的例子,以便于刚好的理解 内部实现
    
    function myNew(constructor) {
        // 创建一个新的空对象  
        const obj = {};  
        // 将新对象的 prototype 属性链接到构造函数的 prototype 对象    
        Object.setPrototypeOf(obj, constructor.prototype);
        // 执行构造函数的代码,并将新创建的对象作为 this 上下文  
        const result = constructor.apply(obj, Array.prototype.slice.call(arguments, 1));  
        // 如果构造函数返回一个对象,则返回这个对象;否则返回新创建的对象  
        return result instanceof Object ? result : obj;
    }
    
    // 由此可得出上面 MyFunction 返回值为引用类型所以是 [4,5,6]