关于原型链继承

        function Parent() {
            this.name = 'kevin';
        }

        Parent.prototype.getName = function () {
            console.log(this.name);
        }

        function Child() {
            // 这里为什么不能这样写
            // Child.prototype = new Parent();
        }

        Child.prototype = new Parent();

        var child1 = new Child();
阅读 2k
3 个回答

var child1 = new Child()会先创建一个对象,然后把Child.prototype赋值给新对象.__proto__,此时Child.prototype还不是new Parent,最后是将构造函数的作用域赋给新对象运行构造函数,所以在Child中设置Child.prototype晚了

那给你整个骚的:

function Parent() {
    this.name = 'kevin';
}

Parent.prototype.getName = function () {
    console.log(this.name);
}

function Child() {
    // 这里为什么不能这样写
//     Child.prototype = new Parent();
    Object.setPrototypeOf(this, new Parent())
}

//Child.prototype = new Parent();

var child1 = new Child();

child1.getName()

哈哈哈哈不要打我

首先,Child的第一个实例的原型链将是残缺的,完全不会继承 Parent 的原型,因为第一次实例化的时候,Child 的原型还未确定。

function A(){A.prototype = new Map()};
t = new A();
console.log(t instanceof Map);
// false

然后,每次实例化Child都要重新实例化一个 Parent 实例,造成了不必要的性能浪费。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题