面试官:手写一下new叭。

304 阅读1分钟

需要注意的点:
1.return一个引用数据类型时,new的新对象是该引用类型对象
2.过程:创建一个空对象,绑定构造函数的原型prototype。再执行构造函数,得到result。

代码

   function myNew(Fn, ...args) {
            const child = {};
            Object.setPrototypeOf(child, Fn.prototype);
            const result = Fn.call(child, ...args)
            return (typeof result === 'object' || typeof result === 'function') && result ? result : child
        }

测试

测试原型方法

 function Fun(c) {
            this.a = 10;
            this.b = 20
            return c
        }

        Fun.prototype.method = function () {
            console.log('原型上的method被访问');

        }

        const fun1 = new Fun(1);
        console.log(fun1.method());
        const fun2 = myNew(Fun, 1)
        console.log(fun2.method());

image.png

测试返回引用数据类型

function Fun(c) {
            this.a = 10;
            this.b = 20
            return c
        }

        Fun.prototype.method = function () {
            console.log('原型上的method被访问');

        }

        const fun1 = new Fun([1]);
        console.log(fun1);
        const fun2 = myNew(Fun, [1])
        console.log(fun2);

image.png

测试返回基本数据类型

function Fun(c) {
            this.a = 10;
            this.b = 20
            return c
        }

        Fun.prototype.method = function () {
            console.log('原型上的method被访问');

        }

        const fun1 = new Fun(1);
        console.log(fun1);
        const fun2 = myNew(Fun, 1)
        console.log(fun2);

image.png

记录记录!