美文网首页
js基础-new关键字

js基础-new关键字

作者: kruz | 来源:发表于2019-06-27 13:35 被阅读0次

    js 的new关键字解析的过程中引擎执行了很多步骤,我们可以自己写一个仿new的函数来实现new关键字。

    js new关键字的作用可以用下面的步骤大致列举一下:

    1. 创建一个空对象obj
    2. 将obj的 _proto_ 属性设置成构造函数的 prototype
    3. 将构造函数绑定这个变量执行
    4. 返回这个对象
    function _new(constructor) {
        //1 创建空的对象
        //2 新对象的prototype指向构造函数
        var obj = {
            "__proto__": constructor.prototype // 必须用这种方式关联原型链
        };
        constructor.apply(obj,[].splice.call(arguments,1)); // 将构造函数绑定这个对象并执行
        return obj; // 返回新对象
    }
    
    //构造函数
    function MyClass(name,time) {
        this.name = name || '';
        this.time = time || '';
    }
    
    //生成一个实例
    var my = _new(MyClass,'kruz_teching','2019');
    console.log(my.name);
    console.log(my.time);
    console.log(typeof my);
    console.log(my instanceof MyClass);
    

    为什么要用new呢?

    new可以实现继承链,new也可以共享原型链节省内存空间

    如下一段代码

    function Person(name){
        this.name = name;
    }
    Person.prototype.sayName = function(){
       console.log(this.name)
    }
    
    var p1 = new Person('zhangsan');
    var p2 = new Person('lisi');
    
    console.log(p1.sayName == Person.prototype.sayName); // true
    console.log(p2.sayName == Person.prototype.sayName);// true
    console.log(p1.sayName());
    console.log(p2.sayName());
    

    可以到p1 和 p2 的sayName函数和 Person.prototype.sayName相等的,实际上是一个函数,就算你new无数个Person对象,sayName函数还是同一份。

    相关文章

      网友评论

          本文标题:js基础-new关键字

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