关于js的prototype与constructor的问题

重新指向了constructor,p2怎么访问不到copy函数?

        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('张三');
阅读 2k
2 个回答

出现这个问题的原因是你使用字面量创建了原型,导致了原型链的重写。图是摘自JS高级程序设计6.3.1,可以解释你遇到的问题:

clipboard.png

原因是在图片描述

Person.prototype.show = function () {
    console.log('show');
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题