L
linc
I am planning on writing a fairly large system in javascript and would
like some advice on using the Douglas Crockford 'beget' function to
implement prototypal inheritance. Searching the internet there don't
seem to be any practical examples of javascript prototypal inheritance
(or maybe I can't find them).
As a start I have created the following example code and would like to
know if I am going in the right direction?
Is there a better way to do this?
Is it correct that any manager object (in this case "bob") gets used
as the base of the new director object?
Object.prototype.beget = function () {
function F() {}
F.prototype = this;
return new F();
};
// Set up Base object
var employee = {
setName: function(name) {
this.name = name;
}
};
// Manager maker
function managerFactory(emp) {
var aManager = emp.beget();
aManager.smokeCigar = function() {
alert(this.name + ' is smoking');
};
aManager.whipEmployees = function() {
alert(this.name + ' is whipping');
};
return aManager;
}
// Director maker
function directorFactory(man) {
var aDirector = man.beget();
aDirector.tiffin = function() {
alert(this.name + ' is enjoying tiffin with secretary');
};
return aDirector;
}
var bob = managerFactory(employee);
bob.setName('bob');
bob.smokeCigar();
var harold = directorFactory(bob);
harold.setName('harold');
harold.whipEmployees();
harold.tiffin();
Thanks,
Lincoln.
like some advice on using the Douglas Crockford 'beget' function to
implement prototypal inheritance. Searching the internet there don't
seem to be any practical examples of javascript prototypal inheritance
(or maybe I can't find them).
As a start I have created the following example code and would like to
know if I am going in the right direction?
Is there a better way to do this?
Is it correct that any manager object (in this case "bob") gets used
as the base of the new director object?
Object.prototype.beget = function () {
function F() {}
F.prototype = this;
return new F();
};
// Set up Base object
var employee = {
setName: function(name) {
this.name = name;
}
};
// Manager maker
function managerFactory(emp) {
var aManager = emp.beget();
aManager.smokeCigar = function() {
alert(this.name + ' is smoking');
};
aManager.whipEmployees = function() {
alert(this.name + ' is whipping');
};
return aManager;
}
// Director maker
function directorFactory(man) {
var aDirector = man.beget();
aDirector.tiffin = function() {
alert(this.name + ' is enjoying tiffin with secretary');
};
return aDirector;
}
var bob = managerFactory(employee);
bob.setName('bob');
bob.smokeCigar();
var harold = directorFactory(bob);
harold.setName('harold');
harold.whipEmployees();
harold.tiffin();
Thanks,
Lincoln.