鍍金池/ 問答/Java  HTML/ 重寫原型對象之后,為什么最初的原型對象還會存在

重寫原型對象之后,為什么最初的原型對象還會存在

        function Person(){}
        var friend=new Person();
        console.log(Person.prototype);            
        Person.prototype={                        
            constructor:Person,
            name:'ytf',
            age:'20',
            job:'student',
            sayName:function(){
                console.log(this.name);
            }
        }
        console.log(Person.prototype);
        console.log(friend.sayName());

clipboard.png

回答
編輯回答
別硬撐

因為你先創(chuàng)建的對象, 舊的原型鏈已經(jīng)建立好了.

        function Person(){}
        // var friend=new Person(); 注釋掉
        console.log(Person.prototype);            
        Person.prototype={                        
            constructor:Person,
            name:'ytf',
            age:'20',
            job:'student',
            sayName:function(){
                console.log(this.name);
            }
        }
        var friend=new Person(); // 在這里創(chuàng)建
        console.log(Person.prototype);
        console.log(friend.sayName());
2018年6月2日 19:58
編輯回答
情殺

拆開給你看,就明白了

var p_old = {};
function Person(){}
Person.prototype = p_old; // Person.prototype 指向的是一個對像

//var friend=new Person(); 差不多等同于如下三條語句
var friend = {};
friend.__porto__= Person.prototype // p_old;
Person.call(friend);

//然后你把 Person.prototype 指向了別的對像
Person.prototype = {
    //...
}

//但 friend.__porto__ 還是指向 p_old
console.log(friend.__porto__ == p_old) //true
2018年8月20日 21:57