重学JS之 原型与原型链

37 阅读1分钟

原型链这里非常简单,如果不太懂的话多写几遍代码即可理解 主要我们记住几个关键词以及他们之间的关系: prototype, constructor, proto,

image.png

       // 原型和原型链
            function Animal() {
                this.egg = 2;
                this.j = 1;
            }
            Animal.prototype.eat = function () {
                console.log("eat");
            };

            let dog = new Animal();

            dog.eat();

            // 原型对象是
            console.log(dog.__proto__);
            // 构造函数的 protoType 是 实例对象的 原型对象
            console.log(Animal.prototype === dog.__proto__); // true

            // 实例对象的 __proto__ 是 原型对象
            console.log(dog.__proto__ === Animal.prototype); // true

            // 原型对象的 constructor 是 构造函数
            console.log(Animal.prototype.constructor === Animal); // true

            // 原型对象的原型对象是 Object.prototype
            console.log(Object.prototype);
            console.log(Animal.prototype.__proto__ === Object.prototype);

            // Object.prototype 的原型对象是 null
            console.log(Object.prototype.__proto__ === null); // true