Search code examples
javascriptobject-create

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


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

Solution

  • 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"