2

I have my master object:

var Person = function() {
    this.canTalk = true;
}

Method I want all sub-objects to inherit:

Person.prototype.greet = function() {
    if( this.canTalk ) {
        console.log( 'Hi, I am ' + this.name );
    }
}

Sub-object that inherits from Employee

  var Employee = function( name, title) {
        Person.call( this );
        this.name = name;
        this.title = title;
    }

Instantiation:

var robert = new Employee( "Robert Rocha", "Software Developer" );
robert.greet();

greet() gets the error: Uncaught TypeError: robert.greet is not a function

What am I doing wrong?

1
  • 2
    The Employee prototype is not inheriting from the Person prototype. You are calling the Person constructor, but not getting any of the data from the Person prototype. Commented Jun 17, 2015 at 23:27

2 Answers 2

4

You need to extend the prototype of Employee.

Employee.prototype = Object.create(Person.prototype);
Employee.prototype.constructor = Employee;
Sign up to request clarification or add additional context in comments.

4 Comments

I thought that simply assigning a value to the prototype would cause all sub-objects to inherit.
Ahh ok so I think I understand. The Object.prototype statement is like saying, "I want to extend blah to this current object" so to speak, and the Object.create()` specifies what object it is that you are extending?
not really. Object.prototype already exists so I'll use MyFunc.prototype is I want all instances of MyFunc to have these properties. Object.create is merely copying it.
@RobertRocha Just fyi, to get the actual prototype of any given object, you do Object.getPrototypeOf(obj).
-2

The key thing you need to do is set the prototype chain. You correctly called the parent constructor and passed it the value of this. You can do this very simply:

Employee.prototype = Person.prototype;

However, now when you add a method to Person, Employee will have access to it as well. If you have a special use case this will work but typically you won't want to do this.

Using the more common method, and when you add a method to Employee.prototype it will not be available to Person.

Employee.prototype = Object.create(Person.prototype);

Note that you are still over-writing Employee.prototype and need to define methods after this over-write.

2 Comments

It "works", yes, but is a very bad practise - you're not setting a prototype chain here

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.