Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript prototyped inheritance and object properties

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?

like image 641
dr jerry Avatar asked Jan 04 '12 09:01

dr jerry


1 Answers

When you instantiate a new Employee, all properties of Person are copied. As this is a shallow copy, pete and bob share the same location object. For your problem, there does not seems a very good solution. You can either use a framework or do a hack like this:

function Employee() { Person.apply(this); };

This calls the Person constructor in the context of the this object.

The MDC has more info on this: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/apply

like image 110
Kosta Avatar answered Sep 20 '22 11:09

Kosta