I am currently exploring the concept of prototyped inheritance in JavaScript for a function. This process is well documented in Wikipedia's javascript article. It functions smoothly when dealing with simple JavaScript types:
function Person() {
this.age = 0;
this.location = {
x: 0,
y: 0,
absolute: false
};
};
function Employee() {};
Employee.prototype = new Person();
Employee.prototype.celebrate = function () {
this.age++;
}
var pete = new Employee();
pete.age = 5;
pete.celebrate();
var bob = new Employee();
bob.celebrate();
console.log("bob is " + bob.age + " pete is " + pete.age);
By setting
Employee.prototype = new Person();
, all properties and methods of Person are inherited by Employee, which is a crucial aspect of inheritance.
As expected, the output is: bob is 1 pete is 6
Now, I am experimenting with altering pete's location (after celebrating):
pete.celebrate();
pete.location.absolute=true;
When checking bob's location.absolute, it displays: true
. This result is unexpected as I did not modify bob's location and anticipated it to retain the initial value defined in Person, causing issues in my implementation.
Initially, I believed the output should be false. I understand that I may need to clone the location object from the original Person, but I am uncertain about where and how to execute this action. Are there any alternative techniques for handling inheritance effectively?