关于es6 class的问题

class Person{
            constructor(name){ 
                this.name = name;
            }
            greet(){
                 
                console.log('Hello,my name is ' + this.name + 'and I am ' + this.age);
            }
        }


class Max extends Person { 
            constructor(age){
                super('Max');
                this.age = age;
            }

            greet(){
                console.log('haha');
            }
            greetTwice(){
                super.greet();
                this.greet();
            }
        } 

let max = new Max(27);
        max.greetTwice();
    
        console.log(max.__proto__ == Max.prototype); //true;
        console.log(max.__proto__ == Person.prototype); //false;

为啥Max是继承了Person,但是他们的prototype却不一样?

阅读 2.9k
2 个回答

要是相等才怪呢!!!

帮你画了一张图,对于class Person和class Max有:

图片描述

从图中可以得出:

max.__proto__ === Max.prototype;

max.__proto__.__proto__ === Max.prototype.__proto__ === Person.prototype === Max.__proto__.prototype

JS 的原型链,原型有链式关系。是存在多个原型,向上指向更父级。不是说最终只有一个原型。(那么没法实现覆盖了)

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