2021-03-10 理解 new 操作符

    我自己总结的new操作流程
    1. 创建一个对象
     2.  Constructor 连接object 原型链
    3. Constructor的 this 指向调用的地方
    4. 返回对象
    代码实现:
   function objectFactory() {
    var obj = new Object(),

        Constructor = [].shift.call(arguments);

    obj.__proto__ = Constructor.prototype;

    var ret = Constructor.apply(obj, arguments);

    return typeof ret === 'object' ? ret : obj;
}


   var ret = Constructor.apply(obj, arguments); 
  /**
   * 解释如下 如果这个函数直接了对象
   * 
   */
   function Otaku (name, age) {
      this.strength = 60;
      this.age = age;

      return {
          name: name,
          habit: 'Games'
      }
  }

  var person = new Otaku('Kevin', '18');

  console.log(person.name) // Kevin
  console.log(person.habit) // Games
  console.log(person.strength) // undefined
  console.log(person.age) // undefined





你可能感兴趣的:(2021-03-10 理解 new 操作符)