鍍金池/ 問答/HTML/ 關(guān)于js的prototype與constructor的問題

關(guān)于js的prototype與constructor的問題

重新指向了constructor,p2怎么訪問不到copy函數(shù)?

        function Person(name) {
            this.name = name;
        }

        Person.prototype.copy = function() {
            return new this.constructor(this.name);
        }
        var p1 = new Person('李四');
        //console.log(Person.prototype);
        Person.prototype = {
            show: function() {
                console.log('show');
            }
        }
        Person.prototype.constructor=Person;
        //console.log(Person.prototype);
        var p2 = new Person('張三');
回答
編輯回答
不二心

出現(xiàn)這個(gè)問題的原因是你使用字面量創(chuàng)建了原型,導(dǎo)致了原型鏈的重寫。圖是摘自JS高級(jí)程序設(shè)計(jì)6.3.1,可以解釋你遇到的問題:

clipboard.png

2018年7月21日 15:44
編輯回答
柒槿年

原因是在圖片描述

Person.prototype.show = function () {
    console.log('show');
}
2017年5月12日 23:41