Constructor of the object created using Object.create(someprototype) in javascript

125 Views Asked by At

Objects created using Object.create(someObj.prototype) has it's constructor as someObj, then how come when I try to access the properties of someObj, then it gives as undefined?

function foo(){
    this.name1 = "Name";
    this.otherName1 = "someOtherName";
}

var fooObj = new foo();
console.log(fooObj.name1); // Name

var barObj = Object.create(foo.prototype);

console.log(barObj.constructor);  
   //Outouts: 
  // function foo(){
 //    this.name1 = "Name";                                                                                                         

 //      this.otherName1 = "someOtherName" ;
//    }


//Then why not able to access this?
console.log(barObj.name1); Outputs; // undefined
2

There are 2 best solutions below

6
Nick Zuber On BEST ANSWER

It's simply because you haven't called the constructor yet.

Consider the following:

barObj.constructor(); // <--- this will call the constructor function and set this.name1 and this.otherName1
console.log(barObj.name1); // Outputs: "Name"
0
Venkat On

Here barObj is just an object linked to foo prototype object.Object.create won't call foo function until you call it explicitly. See below code.

foo.call(barObj) will call foo function with barObj as it's context. Means this in foo function refers to barObj.

function foo(){
    this.name1 = "Name";
    this.otherName1 = "someOtherName";
}

var fooObj = new foo();
//console.log(fooObj); // Name

var barObj = Object.create(foo.prototype);
foo.call(barObj)

//Outouts: 
// function foo(){
//  this.name1 = "Name";                                                                                                         

//  this.otherName1 = "someOtherName" ;
//}


//Then why not able to access this?
console.log(barObj.name1);