Search code examples
javascriptjsonecmascript-6ecmascript-5prototype-chain

How to link two constructors and inherit them as prototype to an Object?


I am working with prototypes in JavaScript (I am new to JS) and stuck with the following snippet of JS code:

I have created two functions:

Function 1

function sample1() {
    this.uname = "Andrew";
}

Function 2

function sample2() {
    this.age = 21;
}

I inherited the properties of sample2 to sample1 as follows:

sample1.prototype = sample2; 

Upto this, everything works fine, like I could see sample1 having sample2 as its prototype. But, the problem is with the creation of an Object using sample1 which contains the property of sample2.

let test = new sample1;

Now, trying to access the property of sample1 gives the correct output.

test.uname;

But, trying to access age gives output as undefined.

Question:

How to access the age property using test Object?

Note: The above is tried using Chrome Developer Tools - Console

Thanks.


Solution

  • Your uname and age properties are created by the constructors directly on each instance that they initialise. There is no point in using prototypical inheritance here. Just run both constructors:

    function sample2() {
        this.age = 21;
    }
    function sample1() {
        sample2.call(this); // runs the other constructor on this instance
        this.uname = "Andrew";
    }
    

    This works quite like a super call when overriding methods.

    I am working with prototypes in JavaScript

    Not yet :-) Your prototype objects are empty.

    I inherited the properties of sample2 to sample1 as follows:

    sample1.prototype = sample2; 
    

    Uh, you shouldn't do that. sample2 is a function object, that's nothing you'd usually want anything to inherit from. Notice that sample1.prototype is what all instances created using new sample1 will inherit from - they're not functions. You probably are looking for

    sample1.prototype = Object.create(sample2.prototype);