Prototype inheritance

Prototype inheritance
0.0 0

#1

I have written out a small program with comments on the bits I am struggling to grasp. Could anyone help cement my understanding? Apologies if it’s not the best way to get some answers, I just thought it might help if you could see my thought process whilst trying to grasp this. I have a fairly solid understanding of Java OOP.

function Person(first, last, age, gender, interests) {

let name = { //this field is private we can use getters and setters

first,

last

};

this.age = age;

this.gender = gender;

this.interests = interests;

this.getName = function () { //getter for private field

return name[“first”] + " " + name[“last”];

}

this.setName = function(first, last) {//setter for pvt field

name[“first”] = first;

name[“last”] = last;

} };

Person.prototype.greeting = function() { //we can then define methods on the prototype

//that use these getters / setters

return "Hello, my name is " + this.getName();

}

//new object that will inherit from person

function Teacher (first, last,age,gender,interests) {

Person.call(this, first, last, age, gender, interests);//kind of like java super();

let subject = “maths”; //adds own property maths

this.getSubject = function()

{ //could also add a setter

return subject;

} }

console.log(Object.getOwnPropertyNames(Teacher.prototype))

//at this point teacher has a constructor property (how, when the function itself is the constructor?)

Teacher.prototype = Object.create(Person.prototype)

//now the prototype of Teacher is the prototype of Person (at this point is Teacher completely identical to person? I understand that this allows us to inherit, but doesn’t this statement overwrite Teachers own Prototype and replace it with Persons? Or does Teacher still have its own individual prototype that can be added to, without adding to Person.prototype?)

console.log(Teacher.prototype) //its prototype is person {}

Teacher.prototype.constructor = Teacher;//why does this need to be done? What happens if this isn’t done?


#2

since you mention you know java, i thought I should share this: https://blog.angular-university.io/javascript-for-java-developers/


#3

Very helpful, reading through it now. Thanks a lot, exactly what I needed.