chaonextdoor
chaonextdoor

Reputation: 5139

A JavaScript inheritance example

For example, I have a person constructor as follows:

function Person(name) {
    var username = name;
    return {
        getName: function() {return username;},
        setName: function(name) {username=name;}
    }
}

Then I want to create another Employee constructor which would inherit from the Person constructor and has a getId method that returns an auto-incremented id value for every object created out of the Employee constructor. For example,

var employee1 = new Employee('foo');
employee1.getName() // will output foo
employee1.getId() // will output 1
var employee2 = new Employee('qoo');
employee2.getName() // will output qoo
employee2.getId() // will output 2

The problem is I'm a little bit confused about how to create an id variable on Employee constructor that it only gets called once and then each object will get a fixed auto-incremented value. How should I set up the Employee constructor and the inheritance?

Upvotes: 1

Views: 178

Answers (1)

Bergi
Bergi

Reputation: 665362

Given your Person constructor, you do not want to use prototypal inheritance but parasitic one.

The Employee constructor will be quite similar in the regard of creating local variables and defining local functions, only that the id will be initialized by incrementing a static counter instead of a paramter:

Employee.counter = 0;
function Employee(name) {
    var that = Person(name);
    var id = Employee.counter++;
    that.getId = function() { return id; };
    return that;
}

Upvotes: 1

Related Questions