Вопрос

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

Consider the following code:

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

console.log( new Person() );

The console will show:

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() );

The console will show:

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

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
Это было полезно?

Решение

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() );

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

Demo: http://jsfiddle.net/jfriend00/CJF3L/

Другие советы

It is correct, you set Person prototype with an instance of mammal and added a property personaction.

I assume personaction is not a constructor so it should not be capitalizes, its better to use object.create instead of creating an instance of parent to set the prototype part of inheritance.

More info here: Prototypical inheritance - writing up

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top