實現new關鍵字


一、new做了什么
1.創建了一個全新的對象。
2.這個對象會被執行[[Prototype]](也就是__proto__)鏈接。
3.生成的新對象會綁定到函數調用的this。
4.通過new創建的每個對象將最終被[[Prototype]]鏈接到這個函數的prototype對象上。
5.如果函數沒有返回對象類型Object(包含Functoin, Array, Date, RegExg, Error),那么new表達式中的函數調用會自動返回這個新的對象。

<!-- 解釋2
先理清楚 new 關鍵字調用函數都的具體過程,那么寫出來就很清楚了
首先創建一個空的對象,空對象的__proto__屬性指向構造函數的原型對象
把上面創建的空對象賦值構造函數內部的this,用構造函數內部的方法修改空對象
如果構造函數返回一個非基本類型的值,則返回這個值,否則上面創建的對象
-->
        <script type="text/javascript">
            function newOperator(ctor){
                if(typeof ctor !== 'function'){
                  throw 'newOperator function the first param must be a function';
                }
                newOperator.target = ctor;
                var newObj = Object.create(ctor.prototype);
                var argsArr = [].slice.call(arguments, 1);
                var ctorReturnResult = ctor.apply(newObj, argsArr);
                var isObject = typeof ctorReturnResult === 'object' && ctorReturnResult !== null;
                var isFunction = typeof ctorReturnResult === 'function';
                if(isObject || isFunction){
                    return ctorReturnResult;
                }
                return newObj;
            }
            
            // es6版本
            function _new(fn, ...arg) {
                const obj = Object.create(fn.prototype);
                const ret = fn.apply(obj, arg);
                return ret instanceof Object ? ret : obj;
            }
            
            function Student (){
                this.name = '1'
            }
            Student.prototype.sayName = func
            
            let student = _new(Student)
            
            console.log(student.__proto__ === Student.prototype) //實例的__proto指向構造函數的原型
        </script>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM