手写实现new方法,以及修改原型链的几种方法.

60 阅读1分钟
  <script>
  function Person(name){
    this.name = name
  }
  function _new(_constructor,...args){
    //先判断传参是否是符合条件的构造函数
    if(!_constructor.hasOwnProperty("prototype")){
      throw new TypeError('_constructor is not a constructor')
    }
    // 创建新对象
    //new方法通过构造函数新建对象实例的过程,其本质是将实例的隐式原型,指向了构造函数的prototype属性。
    //方法1
    let obj = {}
    obj.__proto__ = _constructor.prototype
    //方法2
    // let obj = Object.create(_constructor.prototype)
    //方法3
    // let obj =  {}
    // 参数1:被修改对象,参数2:指向的对象
    // Object.setPrototypeOf(obj,_constructor.prototype) 
    // 构造函数的this指向该对象,也就是obj添加构造函数的属性和方法
    let res =  _constructor.apply(obj,args)
    //如果Person构造函数有返回值,直接返回该返回值
    if(res!==null&&(typeof res === "object"||typeof res ==="function")){
      return res
    }
    return obj
  }
  let p = _new(Person,'xiaoming')
  console.log(p.name,p instanceof Person)//'xiaoming'
  </script>
  • 看到这了,点个赞吧!