Accessing the object property inherited from the parent

function A(){
    this.a=65;
}
A.prototype={
    constructor:A,
    getVal(){
        return this.a;
    }
};
function B(){
    this.b=66;
}
B.prototype=Object.create(A.prototype);
B.prototype.constructor=B;
let c=new B();
console.log(c.getVal());

In the code above I was kinda hoping to get the value of a, i,e 65 but it returned ‘undefined’.
When I changed the B.prototype=Object.create(A.prototype);to B.prototype=new A();
I got the desired result. Can someone explain this to me? What is actually happenning?

`

what is not clear?
you first create a function/object
then add a function getVal in the prototype of A
and try inherit it down the lines to c
i tested it it works fine everything is inherited to c i guess

I guess I misstate my question. Let me make my code simpler and restate the question:

function A(){
    this.a=65;
}
A.prototype={
    constructor:A,
    getVal(){
        return this.a;
    }
};
let test1=Object.create(A.prototype);
console.log(test1.getVal()); //returns undefined

Why is this returns ‘undefined’ instead of 65?

Change this and try:

let test1 = new A();

Ok , in his case A it is a class. Why not to be used as intended?

Makes sense, I just want to bring forward that if you attempt to use es5 class constructor you don’t need Object.create() to declare test1 as a instance of A class. (This is what we want here? right?)
vronra I believe that you have to research a bit about classes and the use of Object.create().

Some suggestions : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create

Highly recommend : https://github.com/getify/You-Dont-Know-JS/tree/master/this%20%26%20object%20prototypes

1 Like