js手写new操作符

每天一道手写题


手写new核心代码

 function myNew(fn, ...arg) {
            let obj1 = {}
            if (fn.prototype)
                obj1.__proto__ = fn.prototype

            let res = fn.apply(obj1, arg)
            if (res && (typeof res == 'function' || typeof res == 'object'))
                return res
            return obj1
        }

测试

 function myNew(fn, ...arg) {
            let obj1 = {}
            if (fn.prototype)
                obj1.__proto__ = fn.prototype

            let res = fn.apply(obj1, arg)
            if (res && (typeof res == 'function' || typeof res == 'object'))
                return res
            return obj1
        }

        function a(name, age, height) {
            this.name = name
            this.age = age
            this.height = height
        }
        a.prototype.sayHi = () => {
            console.log('my name is Li Hua');
        }
        let p = myNew(a, 'giegie', 18, 180)
        console.log(p);
        p.sayHi()

猜你喜欢

转载自blog.csdn.net/A_D_H_E_R_E/article/details/120817621