Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
24
rated 0 times [  26] [ 2]  / answers: 1 / hits: 16484  / 13 Years ago, tue, may 3, 2011, 12:00:00

I've been asked to port some of our PHP code across to JavaScript, so that more of our logic runs client-side. What'd I'd like is a simple example that shows:




  • a namespace (Package) containing two classes (Master and Slave)

  • the Master class has a property p, a function m and a constructor that takes a single argument to set the initial value of p

  • the Slave class inherits both p, the constructor and m from the Master class



I don't mind using some sort of existing framework, but it must be lightweight -- ideally no more than 200 LOC (un-minified).



Here's my attempt, FWIW:



var Package = {};

Package.Master = function(pValue) {
this.p = pValue;
this.m = function() {
alert(mmmmm);
}
}

Package.Slave = function(pValue) {
// this will inherit from Package.Master
}

// one of the many online examples:
// http://kevlindev.com/tutorials/javascript/inheritance/index.htm
KevLinDev.extend = function(subClass, baseClass) {
function inheritance() {}
inheritance.prototype = baseClass.prototype;

subClass.prototype = new inheritance();
subClass.prototype.constructor = subClass;
subClass.baseConstructor = baseClass;
subClass.superClass = baseClass.prototype;
}

KevLinDev.extend(Package.Slave, Package.Master);

More From » inheritance

 Answers
54

I'm quite a fan of John Resig's Simple Javascript Inheritance.



E.g.:



var Package = {};
Package.Master = Class.extend({
init: function(pValue) {
this.p = pValue;
},
m: function() {
alert(mmmmm);
}
});

Package.Slave = Package.Master.extend({
init: function(pValue) {
this._super(pValue);
}
});

var slave = new Package.Slave(10);
slave.m();

[#92424] Monday, May 2, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
georgeh

Total Points: 193
Total Questions: 103
Total Answers: 111

Location: United States Minor Outlying Island
Member since Sat, May 28, 2022
2 Years ago
;