I'm trying to apply prototyped inheritance to a function in Javascript. It's all pretty plain and even described in Wikipedia's javascript lemma. It works if my properties are 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);
With Employee.prototype = new Person();, all Person's properties and (prototyped) methods are inherited by Employee, which is fundamental to inheritance.
This works as expected: bob is 1 pete is 6
Now I'm starting to fiddle with pete's location (after celebrating)
pete.celebrate();
pete.location.absolute=true;
Displaying bob.location.absolute shows: true, which is contra intuitive (I didn't touch bob's location so I expect it to have the initial value declared in Person) and ruins my solution.
In my initial understanding this should have been false. I do realize that I probably should clone the location object from the initial Person, but I'm not sure where or how to do this. And if there are maybe better techniques for inheritance?