What exactly does the new operator of the front-end interview do?


What exactly does the new operator do?

  • (1) First, an empty object is created.
  • (2) Set the prototype, and set the prototype of the object to the prototype object of the function.
  • (3) Let the this of the function point to this object and execute the code in the constructor
  • (4) Determine the return value type of the function. If it is a value type, it returns the created object, if it is a reference type, it returns an object of this reference type.

    Realize it?

    function objectFactory(){
      let newObject = null,
      construct = Array.prototype.shift.call(anguments),
      result = null
      // 参数判断
      if(typeof construct !== 'function'){
          console.error('type error')
      // 新建一个空对象,对象的原型为构造函数的prototype对象
      newObject = Object.create(construct.prototype)
      // 将this 指向这个新建对象,并执行
      result = construct.apply(newObject,arguments)
      // 判断返回对象
      if flag = result && (typeof result === 'object' || typeof result === 'boolean')
      return flag ? result : newObject

    Determine the return value type?

    For the return value, when the constructor returns a basic data type, the result returned at this time is the object we created newObject . When the constructor returns a reference type object || function , the return value result The apply function re-binds the this point, which means that the value of the reference type returned by the constructor function is what the current return value type is.
    The specific code can be seen:

    // 构造函数返回引用数据类型Object
    let foo = objectFactory([function Foo(){ this.name = 'name'; return new Object("name") },1])
    console.log(foo,"--------")  // [String: 'name'] --------
    // 当构造函数返回值为Object("name"),所以返回值此时返回result,程序又通过apply改变了this的指向,指向了构造函数的返回值Object('name'),所以此时使用new操作符的返回值为引用数据类型[String: 'name']
    // 构造函数返回基本数据类型String
    let foo = objectFactory([function Foo(){ this.name = 'name'; return 'sss' },1])
    console.log(foo,"--------")  // Foo { name: 'name' } --------
    // 当构造函数返回值为字符串,所以此时返回newObject,则此时的返回值为Foo
阅读 683


397 声望
742 粉丝
0 条评论


397 声望
742 粉丝