Reputation: 1
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
Reputation: 60597
Your problem is two-fold.
Object.create
should be passed the prototype
, not the constructor. In this case, you should use Object.create(person.prototype);
, not Object.create(person);
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.
call
parent constructor.person.call(this);
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);
person.prototype.say = "hello";
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
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
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