1. 程式人生 > >prototype和new的底層實現

prototype和new的底層實現

bject span console prot pan var col tor 包含

    <script type="text/javascript">
        function A(){
            this.name = "jack";
            this.age = 18;
            height = 180;
            this.action = function(v){
                console.log(this===v);
            }
            
        };
        A.prototype.price = 888888888;
    
// 首先:A的原型鏈prototype是個對象Object // 然後:price是對象A原型鏈prototype的屬性 console.log(A.prototype.price); // A是沒有price屬性的哦 console.log(A.price); // 最後:原型鏈prototype中含有 構造器constructor和原型__proto__ console.log(A.prototype); // 原型鏈的constructor就是構造函數 A console.log(A.prototype.constructor); console.log(A
=== A.prototype.constructor); // __proto__中含有很多固有屬性 console.log(A.prototype.__proto__); // 所以說:構造函數屬性的使用都是靠 prototype來實現的。 // 那麽 new A() 是怎麽回事? // new A(); 不僅有 prototype的屬性,也有 var a = new A(); // a除了this包含的屬性外還有 __proto__ console.log(a); // a能使用 A的的屬性哦 console.log(a.age);
// 因為a的就是A中的this a.action(a); // a能使用 A.prototype的屬性哦 console.log(a.price); // 哎呦。a的原型__proto__和 A的原型鏈prototype是一樣的 // 那麽 new A() 是把 a.__proto__引用指向了A.prototype咯??? console.log(a.__proto__ === A.prototype) // 綜合上面 的結論,那麽 a能使用 prototype屬性的原因是因為 a原型的引用指向了 A.prototype // a能使用A中的屬性是因為。A中的this === a; </script>

prototype和new的底層實現