详细解读New创建过程(五)

186 阅读1分钟

类的实例化

使用new操作符实例化类等于使用new调用其构造函数,JS解释器知道使用new和类意味着应该使用constructor函数进行实例化!

new调用类的构造函数会执行如下操作:

  1. 创建空对象
  2. 空对象的 [[Prototype]] 指针被赋予 构造函数的 prototype
  3. 构造函数内部this指向空对象
  4. 指向构造函数内部代码(真正开始赋值)
  5. 构造函数无返回,则返回this;否则返回刚创建的实例

对于步骤5,如果返回其他对象,则这个对象不能关联到构造函数,详细见下

😀创建一个 class

 const Person = class {
     constructor(flag = false) {
       if (flag) {
         return {
           bar: "bar"
         }
       }
       return this;//这行代码可以不写,因为是默认的
     }
   }

😀Person的原型上添加 call 方法

 Person.prototype.call = function(){
     console.log("hello world!");
 }

😀实例化 p1和p2,但是返回对象不同

 let p1 = new Person();// constructor返回 this 的情况
   let p2 = new Person(true);//返回 非this对象
   console.log(p2 instanceof Person); //false
   p1.call();//hello world!
   p2.call();//报错:  Uncaught TypeError: p2.call is not a function

可以看出p2已结丢失了与 Person类的关联,因此也就丢失了call方法