JS new关键字

250 阅读1分钟

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

  1. 在内存中创建一个新对象。
  2. 这个新对象内部的[[Prototype]]指针被赋值为构造函数的 prototype 属性。
  3. 构造函数内部的 this 被赋值为这个新对象(即 this 指向新对象)。
  4. 执行构造函数内部的代码(给新对象添加属性)。
  5. 如果构造函数返回非空对象,则返回该对象;否则,返回刚创建的新对象。

简单实现:

function newOperation(constructor){
    let args = Array.prototype.slice.call(arguments,1)
    let obj = {}
    obj.__proto__ = constructor.prototype
    let result = constructor.apply(obj,args)
    const isObject = typeof result === 'object'&&result!==null
    const isFunc = typeof result === 'function'
    return isObject||isFunc?result:obj
}