0

Recently I learn about the concepts of prototype, _proto_, and inheritance. I've tried to figure out the output below, but failed...

function test(){
  var a = 1;
  this.b =2;
}
var o1 = new test();
var o2 = Object.create(test);
console.log(test.a);  //undefined
console.log(test.b);  //undefined
console.log(o1.a);    //undefined
console.log(o1.b);    //2
console.log(o2.a);    //undefined
console.log(o2.b);    //undefined

As a javascript rookie, could someone tell me

why there is only "o1.b" able to access the value 2?

Eide
  • 5
  • 1
  • 3
  • Does this answer your question? [Prototypical inheritance - writing up](https://stackoverflow.com/questions/16063394/prototypical-inheritance-writing-up) – Rahul Bhobe Aug 18 '20 at 10:37

2 Answers2

0

First of all, you are doing some things wrong here. Let me break it down. See the comments after each line.

function test(){
  var a = 1; //this variable a is local to this function test only.so it is not part of the o1,o2 objects.
  this.b =2; //this keyword refers to the object on which this function is called.
}
var o1 = new test(); 
var o2 = Object.create(test);//this is not a way to create object using Object.create().. Object.create() takes another object as an argument to create a new object and here you are using test which is a function.
console.log(test.a);  //test is a function not an object
console.log(test.b);  //test is a function not an object
console.log(o1.a);    //since a is local to the function that's why you are getting undefined here
console.log(o1.b);    //here output is 2 because b is an object property and you have assigned its value to 2 in the test function.
console.log(o2.a);    //undefined because o2 is not an object it is a function.
console.log(o2.b);    //undefined because o2 is not an object it is a function.

You can try to implement the above code in this way:

var Test=function test(){
  this.a = 1;
  this.b =2;
}
var o1 = new Test();
var o2 = Object.create(o1);

console.log(o1.a);    
console.log(o1.b);    
console.log(o2.a);    
console.log(o2.b);
Dharman
  • 30,962
  • 25
  • 85
  • 135
EhtU
  • 41
  • 4
  • Object.create() can create both Object and Function, isn't it? – Eide Aug 18 '20 at 13:59
  • please refer https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create and if you have found my answer useful you can accept it. – EhtU Aug 19 '20 at 07:30
0

In javascript functions are also objects so test, o1 and o2 are objects, they have properties, this the result when visualizing on the console:

enter image description here

console.log(test.a);  //undefined ---> test has no a nor b property
console.log(o1.b);    //2         ---> o1 has b property
console.log(o2.a);    //undefined ---> o2 has no a nor b property
user2495207
  • 861
  • 2
  • 10
  • 15