源码系列:new 源码

知识前提:

1、知道原型链, 了解 __proto__ 和 prototype 的基本区别

2、知道 Object.create()和 this 指向

new 字段的实现原理:

文字描述:

1、在钩爪其内部船舰一个新的对象

2、这个对象内部的 __proto__ 属性会被赋值为该构造函数的 prototype 属性

3、让构造器中的 this 指向这个对象

4、执行构造器中的代码

5、如果构造器中没有返回对象或函数,则返回上面创建的对象

代码:

    var _new = function(obj, ...args) {
            if(!obj.hasOwnProperty('prototype')) {
                throw new TypeError(obj,'不是构造器')
            }
            /*
                在钩爪其内部船舰一个新的对象
                这个对象内部的 __proto__ 属性会被赋值为该构造函数的 prototype 属
            */
            let newObj = Object.create(obj.prototype)   
            // 让构造器中的 this 指向这个对象
            // 执行构造器中的代码
            let result = obj.apply(newObj, args)
            // 如果构造器中没有返回对象或函数,则返回上面创建的对象
            if(result != null && (typeof result == 'object' || typeof result == 'function')) {
                return result
            } else {
                return newObj
            }
             
        }
        function Dog(name) {
            this.name = name
            // return {
            //     name: '你的' + name
            // }
            // return function() {
            //     console.log('函数')
            // }
        }
         
        console.log(_new(Dog, '狗子'))

猜你喜欢

转载自blog.csdn.net/A88552211/article/details/128920680