Zurück zu Pi7.eu
BLOG
Superclass and Subclass in JavaScript
// Define a class
function ClassA() {
this.overwriteVariable = 'A';
this.inheritVariable = 'A';
this.inheritFunction = function() {
return 'A';
};
this.overwriteFunction = function() {
return 'A';
};
// if you put alert() or some other functions here (wich is the "cunstructor";) it will also be executed in the SubClass - but there is no way do overwrite it! Only Workarounds can help you then, e.g. a variable that is cheecked to weather to execute the constructor or not, wich is set in the subclass before exectuing "superclass()". Also note, that Parameters of the superclass are not used in the subclass!
}

// Define a subclass from ClassA
function ClassB() { this.superclass=ClassA; this.superclass();
this.overwriteVariable = 'B';
this.newVariable = 'B';
this.newFunction = function() {
return 'B';
};
this.overwriteFunction = function() {
return 'B';
};
}

// Create new instance of ClassB
var testClass = new ClassB();

// Test output:
alert('overwriteVariable: '+ testClass.overwriteVariable +' inheritVariable: '+ testClass.inheritVariable +' newVariable: '+ testClass.newVariable +' inheritFunction(): '+ testClass.inheritFunction()+' newFunction(): '+ testClass.newFunction() +' overwriteFunction(): '+ testClass.overwriteFunction());


This will return:
overwriteVariable: B
inheritVariable: A
newVariable: B
inheritFunction(): A
newFunction(): B
overwriteFunction(): B
Autor: Pierre
erstellt am 22.04.2012 12:16 - aktualisiert am 23.04.2012 18:32
1.905 Aufrufe
...
You can share this Blog on Facebook, Google+ and Twitter! ... yes you can!