美文网首页
JavaScript深入之new的模拟实现

JavaScript深入之new的模拟实现

作者: JAZI | 来源:发表于2020-08-09 10:51 被阅读0次

    new 运算符创建一个用户定义的对象类型的实例或具有构造函数的内置对象类型之一

    也许有点难懂,我们在模拟 new 之前,先看看 new 实现了哪些功能

    // Otaku 御宅族,简称宅
    function Otaku (name, age) {
        this.name = name;
        this.age = age;
    
        this.habit = 'Games';
    }
    
    // 因为缺乏锻炼的缘故,身体强度让人担忧
    Otaku.prototype.strength = 60;
    
    Otaku.prototype.sayYourName = function () {
        console.log('I am ' + this.name);
    }
    
    var person = new Otaku('Kevin', '18');
    
    console.log(person.name) // Kevin
    console.log(person.habit) // Games
    console.log(person.strength) // 60
    
    person.sayYourName(); // I am Kevin
    

    从这个例子中,我们可以看到,实例 person 可以:

    访问到 Otaku 构造函数里的属性
    访问到 Otaku.prototype 中的属性

    接下来,我们可以尝试着模拟一下了。
    因为 new 是关键字,所以无法像 bind 函数一样直接覆盖,所以我们写一个函数,命名为 objectFactory,来模拟 new 的效果。

    因为 new 的结果是一个新对象,所以在模拟实现的时候,我们也要建立一个新对象,假设这个对象叫 obj,因为 obj 会具有 Otaku 构造函数里的属性,想想经典继承的例子,我们可以使用 Otaku.apply(obj, arguments)来给 obj 添加新的属性。

    // 第一版代码
    function objectFactory() {
    
        var obj = new Object(),
    
        Constructor = [].shift.call(arguments);
    
        obj.__proto__ = Constructor.prototype;
    
        Constructor.apply(obj, arguments);
    
        return obj;
    
    };
    

    在这一版中,我们:

    • 用new Object() 的方式新建了一个对象 obj
    • 取出第一个参数,就是我们要传入的构造函数。此外因为 shift 会修改原数组,所以 arguments 会被去除第一个参数
    • 将 obj 的原型指向构造函数,这样 obj 就可以访问到构造函数原型中的属性
    • 使用 apply,改变构造函数 this 的指向到新建的对象,这样 obj 就可以访问到构造函数中的属性
    • 返回 obj

    除此以外所以我们还需要判断返回的值是不是一个对象,如果是一个对象,我们就返回这个对象,如果没有,我们该返回什么就返回什么。

    // 第二版的代码
    function objectFactory() {
    
        var obj = new Object(),
    
        Constructor = [].shift.call(arguments);
    
        obj.__proto__ = Constructor.prototype;
    
        var ret = Constructor.apply(obj, arguments);
    
        return typeof ret === 'object' ? ret : obj;
    
    };
    

    相关文章

      网友评论

          本文标题:JavaScript深入之new的模拟实现

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