JavaScript inheritance not working as expected

I have my main 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 );
    }
}

      

A subject who 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?

+3


source to share


2 answers


You need to extend the prototype Employee

.



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

      

+4


source


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

Employee.prototype = Person.prototype;

      

However, now when you add the Person method, Employee will also have access to it. If you have a special use case, this will work, but usually you won't want to.



Using the more common method, and when you add a method to Employee.prototype, it won't be available to Person.

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

      

Note that you are still overwriting Employee.prototype and need to define methods after this overwrite.

-2


source







All Articles