0

I'm using below code.

var emp = function employee(name, sal) {
  this.empname = name;
  this.sal = sal;
}

emp.prototype.getName = function() {
  return this.empname
};

var man = new emp("manish", 100);
console.log(man.getName()); //prints manish

var man1 = Object.create(emp);
man1.empname = "manish1";
console.log(man1.prototype.getName()); //prints undefined.

can some help me to understand why object create is printing undefined instead manish1.

Peter B
  • 22,460
  • 5
  • 32
  • 69
Manish
  • 1,246
  • 3
  • 14
  • 26
  • 1
    This may help: http://stackoverflow.com/questions/3079887/javascript-inheritance-with-object-create – Rajesh Oct 20 '16 at 09:56

1 Answers1

2

new X() creates a new object with constructor X and prototype X.prototype. Object.create(X) creates a new object with prototype X (and therefore constructor X.constructor).

So you need to call it with the prototype you want:

var man2 = Object.create(emp.prototype);   
man2.empname = "manish2";
console.log (man2.getName()); // prints manish2
joews
  • 29,767
  • 10
  • 79
  • 91