Prototypal inheritance

please bear with my noobishness, but i’ve been trying for many hours to understand what is going on behind this code:

**

function Person() {
document.write(‘constructor: <br/>’+this.constructor); //displays Person constructor
this.name = “Rob Roberson”;
this.age = 31;
}

function Employee() {
document.write(‘<br/>constructor: <br/>’+this.constructor); //displays Person constructor
this.dept = “HR”;
this.manager = “John Johnson”;
}

Employee.prototype = new Person();

var Ken = new Employee();

document.write(‘<br/>’+Ken.constructor); //displays Person constructor
document.write(‘<br/>name:’+ Ken.name + ‘<br/>age:’ + Ken.age + ‘<br/>dept:’ + Ken.dept + ‘<br/>manager:’ + Ken.manager ); //displays all properties correctly


from what i’ve read, every object references a prototype. in this case, the Employee function will automatically reference a prototype with ‘constructor’ as its initial value. this command:

Employee.prototype = new Person();

will replace the Employee function’s prototype to an instance of Person. so now Employee function’s prototype will contain both name and age properties, BUT, and this is where i get lost, ITS CONSTRUCTOR PROPERTY GETS REPLACED! so how does:

var Ken = new Employee();

actually construct an instance of Employee if the reference to its constructor has been replaced by an instance of Person that only contains name and age properties? how is Ken ever initialized by Employee constructor?

thank you for your reply. what i’m confused about is that the code i posted already exhibited inherited properties of the Person constructor. my main source of confusion is how the Employee constructor is ever initialized when its prototype is an instance of Person class (Employee.prototype = new Person). Since the original Employee prototype is overwritten and therefore its constructor too, how is it ever executed?

You could use the apply() method instead, that simulates object inheritance object inheritance in Javascript i.e. Employee will be left as it is, but will also inherit the properties of the Person function. Your code would look something like this:

function Employee() {
document.write(‘<br/>constructor: <br/>’+this.constructor); //displays Person constructor
this.dept = “HR”;
this.manager = “John Johnson”;
Person.apply(this, [null]);
}

In this way the constructor should remain intact