I'm well aware that javascript is not a class based language.
With that being said here is an example of (one of the ways) we do inheritance in JavaScript:
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.introduceSelf = function() {
console.log("My name is " + this.name + " and I'm " + this.age);
}
function Employee(name, age, employeeID) {
Person.call(this, name, age);
this.employeeID = employeeID;
}
Employee.prototype = Object.create(Person.prototype);
Employee.prototype.sayEmployeeID = function() {
console.log('My Employee ID is: ' + this.employeeID);
}
var joe = new Employee('Joe', 22, 42);
joe.introduceSelf() // returns: My name is joe and I'm 22
joe.sayEmployeeID() // returns: My Employee ID is: 42
My question is: how does simply calling Person.call(this, name, age)
within the Employee constructor, result in the object having the name
and age
property when calling new Employee(...)
I understand that it's calling the Person function with the this
being the context within Employee
but It's not clear how the properties get onto the resulting object. What exactly is happening "under the hood?"