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.

1

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.