Zephyrs
Zephyrs

Reputation: 1

Javascript Object.create is not inheriting from the parent

I want the man object inherits from the person object. I could have done it using the new operator, but it should work with Object.create. But why it is not working? The console.log says undefined instead of the expected hello.

function person() {
    this.say="hello";
}

function man() {
    this.name="John Miler";
}

man.prototype = Object.create(person);

var Johnny = new man();

console.log(Johnny.say);  

Upvotes: 0

Views: 54

Answers (3)

Alexander O'Mara
Alexander O'Mara

Reputation: 60597

Your problem is two-fold.

Problem 1:

Object.create should be passed the prototype, not the constructor. In this case, you should use Object.create(person.prototype);, not Object.create(person);


Problem 2:

The say property is added when the constructor is called, and you never call the parent constructor from the child constructor.

There are a couple ways to solve this, depending on your desired behavior.

Option 1, call parent constructor.

person.call(this);

Sample:

function person() {
    this.say="hello";
}

function man() {
    person.call(this);
    this.name="John Miler";
}

man.prototype = Object.create(person.prototype);

var Johnny = new man();

console.log(Johnny.say);  

Option 2, make it a static property.

person.prototype.say = "hello";

Sample:

function person() {
}
person.prototype.say = "hello";

function man() {
    this.name="John Miler";
}

man.prototype = Object.create(person.prototype);

var Johnny = new man();

console.log(Johnny.say);  

Upvotes: 3

Darshan
Darshan

Reputation: 1044

Object.create should be passed the prototype not the constructor.

function person() {
 this.say="hello";
}

function man() {
 this.name="John Miler";
}

man.prototype = Object.create(new person());

var Johnny = new man();

console.log(Johnny.say);

Upvotes: 0

Derlin
Derlin

Reputation: 9881

If what you try to achieve is for a man object to inherit a person object, try this:

// superclass
function Person() {
  this.say = "hello";
}

// superclass method
Person.prototype.doStuff = function() {
  console.info('Stuff done.');
};

// subclass
function Man() {
  Person.call(this); // call super constructor.
  this.name="John Miler";
}

// subclass extends superclass
Man.prototype = Object.create(Person.prototype);
Man.prototype.constructor = Man;


var Johnny = new Man();

console.log(Johnny.say); // hello

Upvotes: 0

Related Questions