Source code series: new source code

Knowledge premise:

1. Know the prototype chain, understand the basic difference between __proto__ and prototype

2. Know what Object.create() and this point to

The implementation principle of the new field:

word description:

1. Ship a new object inside the grapple

2. The __proto__ attribute inside the object will be assigned as the prototype attribute of the constructor

3. Let this in the constructor point to this object

4. Execute the code in the constructor

5. If no object or function is returned in the constructor, the object created above is returned

code:

    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, '狗子'))

Guess you like

Origin blog.csdn.net/A88552211/article/details/128920680