美文网首页
JS new 运算符源码实现

JS new 运算符源码实现

作者: 泰然自若_750f | 来源:发表于2020-03-29 16:51 被阅读0次

    new 运算符创建一个用户定义的对象类型的实例或具有构造函数的内置对象的实例。new 关键字会进行如下的操作:

    1:创建一个空的简单JavaScript对象(即{});
    2:链接该对象(即设置该对象的构造函数)到另一个对象 ;
    3:将步骤1新创建的对象作为this的上下文 ;
    4:如果该函数没有返回对象,则返回this。
    所以我们可以根据四个步骤实现new 运算符;

           function _new(){
                constructor=Array.prototype.shift.call(arguments,1);
                console.log(typeof constructor);
                if(typeof constructor!=='function')
                {
                   throw new TypeError(constructor+' is not a constructor');
               }             
                let obj={};//创建一个空对象
                obj._proto_=constructor.prototype;//步骤二
                //以上两步可以合并为 
                // let obj=Object.create(constructor.prototype);
                constructor.apply(obj,arguments);//步骤三
                 return obj;//返回
            }
      //实例
        function Person(name,sex,age){
                        this.name=name;
                        this.sex=sex;
                        this.age=age;
    
          }
    //测试
    var p=_new(Person,"丽莎","男","12"); //{_proto_: {…}, name: "丽莎", sex: "男", age: "12"}    
    var p=_new("s"); //s is not a constructor
    
    

    相关文章

      网友评论

          本文标题:JS new 运算符源码实现

          本文链接:https://www.haomeiwen.com/subject/ghduuhtx.html