new操作符具体干了什么?

new操作符具体干了什么?

// 构造函数A
    function A(name,age) {
      this.name = name
      this.age = age
    }
    
    function New(func) {
      // func 为传进来的构造函数
      // res 是创建的一个全新对象。
      var res = {};
      // 先判断原型对象存不存在, 存在就把空对象链接到原型对象上去, 最后返回这个对象
      if (func.prototype !== null) {
          res.__proto__ = func.prototype;
      }
      // console.log(arguments);  // [A, 1, 2]
      console.log(Array.prototype.slice.call(arguments, 1)); // [1, 2]
      // 这里相当于把构造函数中的this指向res对象, 并传入参数
      // ret表示func函数的返回值, 没有return则为undefined
      var ret = func.apply(res, Array.prototype.slice.call(arguments, 1)); 
      // 执行完上一行代码, res为{name: 1, age: 2}, ret为undefined
      console.log(res, ret);
      if ((typeof ret === "object" || typeof ret === "function") && ret !== null) {
          return ret;
      }
      // 自我理解, if判断语句的目的是判断func函数是不是标准构造函数,还是普通函数(如果含有return函数且返回的是Object,Functoin, Array, Date, RegExg, Error,那么就是普通函数, 此时返回return的内容, 如果是简单数据类型或者没有return,则返回res对象)
      return res;
    }
    var obj = New(A, 1, 2);
    // 等同于
    // var obj = new A(1, 2);
    console.log(obj);

针对上述对ret的if判断进行解释:

function B(){
      return {ttt: 1000, hhh: 2000}
    }
    function NewN(func) {
      var res = {}
      if(func.prototype !== null){
        res.__proto__ = func.prototype
      }
      var ret = func.apply(res, Array.prototype.slice.call(arguments, 1))
      console.log(ret); // {ttt: 1000, hhh: 2000}
      console.log(res); // {}
      if( (typeof ret === 'object' || typeof ret === 'function') && ret !== null) {
        return ret
      }
      return res
    }
    var obj1 = NewN(B, 100, 200);
    console.log(obj1); //{ttt: 1000, hhh: 2000}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值