3

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?

Robert
  • 10,126
  • 19
  • 78
  • 130
  • 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. – jfriend00 Jun 17 '15 at 23:27

2 Answers2

4

You need to extend the prototype of Employee.

Employee.prototype = Object.create(Person.prototype);
Employee.prototype.constructor = Employee;
Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
  • I thought that simply assigning a value to the prototype would cause all sub-objects to inherit. – Robert Jun 17 '15 at 23:26
  • 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? – Robert Jun 17 '15 at 23:39
  • 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. – Daniel A. White Jun 17 '15 at 23:40
  • @RobertRocha Just fyi, to get the actual prototype of any given object, you do `Object.getPrototypeOf(obj)`. – Shashank Jun 17 '15 at 23:45
-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.

cade galt
  • 3,843
  • 8
  • 32
  • 48
  • It "works", yes, but is a very bad practise - you're not setting a prototype *chain* here – Bergi Jun 18 '15 at 00:34
  • Just for reference: https://stackoverflow.com/questions/11088365/why-wouldnt-i-use-child-prototype-parent-prototype-rather-than-child-prototype-new-parent – Bergi Jun 18 '15 at 01:21