Accessing the object property inherited from the parent

Accessing the object property inherited from the parent
0

#1
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?

`


#2

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


#3

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?


#4

Change this and try:

let test1 = new A();


#5

Because in the above code you assigned A.prototype to test1. The prototype does not have a property named “a”. If you added a property named “a” and give it a value, (see below) then it would return something.

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

#6

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


#7

Are you asking me? I was not suggesting he add an “a” property to the prototype. I was just explaining why he was seeing undefined in the console instead what he expected (65).


#8

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


#9

That is very true and a good point to make.

I assume the OP is working through the this FCC challenge, a tutorial or information found elsewhere and is just trying to testing out his understanding of the concepts being presented.