本文介绍了控制台中正确的原型链(具有对象继承)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请原谅我被一些有效的东西所困扰,但没有在控制台上按预期"显示.

Forgive me for being bothered by something that works, yet not showing up 'as expected' on the console.

考虑以下代码:

function Person() {};
Person.prototype.PersonAction = function() {}

console.log( new Person() );

控制台将显示:

Person {PersonAction: function}
    __proto__: Person
        PersonAction: function () {}
        constructor: function Person() {}
        __proto__: Object

这一切都很好.现在考虑这段代码:

That's all good. Now consider this code:

function Mammal() {};
Mammal.prototype.MammalAction = function() {}

function Person() {};
Person.prototype = new Mammal();
Person.prototype.PersonAction = function() {}

console.log( new Person() );

控制台将显示:

Person {PersonAction: function, MammalAction: function}
    __proto__: Mammal
        PersonAction: function () {}
        __proto__: Mammal
            MammalAction: function () {}
            constructor: function Mammal() {}
            __proto__: Object

虽然这有效(我理解它为什么会这样显示),请注意 Mammal 的两个原型,其中最上面的一个具有 PersonAction.这就是我所困扰的一点.

While this works (and I understand why it shows up this way), notice two prototypes of Mammal, with the top one having PersonAction. That's the bit I'm bothered by.

我想知道是否有任何方法可以做到这一点,我假设是正确的":

I wonder if there is any way to get this right, by 'right' I assume:

Person {PersonAction: function}
    __proto__: Person
        PersonAction: function () {}
        constructor: function Person() {}
        __proto__: Mammal
            MammalAction: function () {}
            constructor: function Mammal() {}
            __proto__: Object

推荐答案

这将通过将构造函数设置回它应该是的样子并使用 Object.create() 作为原型来实现:

This will do it by setting the constructor back to what it's supposed to be and using Object.create() for the prototype:

function Mammal() {};
Mammal.prototype.MammalAction = function() {}

function Person() {};
Person.prototype = Object.create(Mammal.prototype);
Person.prototype.PersonAction = function() {}
Person.prototype.constructor = Person;

console.log( new Person() );

它在 Chrome 中为您提供:

It gives you this in Chrome:

Person {PersonAction: function, constructor: function, MammalAction: function}
    __proto__: Person
        PersonAction: function () {}
        constructor: function Person() {}
       __proto__: Mammal
           MammalAction: function () {}
           constructor: function Mammal() {}
           __proto__: Object

演示:http://jsfiddle.net/jfriend00/CJF3L/

这篇关于控制台中正确的原型链(具有对象继承)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 15:40