I meet a problem when using javascript to implement interface and its inheritance.
The contents and idea are from the book Learning JavaScript Design Pattern. I tried using its interface code, and hope the way I using can make it act much like C#. The code I used is as following:
var Interface = function(name, methods) {
if (arguments.length != 2) {
throw new Error("Interface constructor called with " + arguments.length +
"arguments, but expected exactly 2.");
}
this.name = name;
this.methods = [];
for (var i = 0, len = methods.length; i < len; i++) {
if (typeof methods[i] !== 'string') {
throw new Error("Interface constructor expects method names to be " +
"passed in as a string.");
}
this.methods.push(methods[i]);
}
};
function extend(subClass, superClass) {
var F = function() {};
F.prototype = superClass.prototype;
subClass.prototype = new F();
console.log(subClass.name);
console.info(subClass);
subClass.prototype.constructor = subClass;
subClass.superclass = superClass.prototype;
if (superClass.prototype.constructor == Object.prototype.constructor) {
superClass.prototype.constructor = superClass;
}
}
var Composite = new Interface('Composite', ['add', 'remove', 'getChild']);
console.log(Composite.name);
console.info(Composite);
console.log(Composite.__proto__.constructor.name);
var testinterface = function(name ,methods) {
Composite.call(this, name, methods);
};
extend(testinterface, Composite);
But when executing the codes, the error message showing: Cannot read property 'constructor' of undefined.
Something indeed is wrong when I declare function testinterface, but I don't know why, since in the function body of extend, the console.log output explain that the testinterface is still a function declaration, not have any prototype, even constructor.
Is there any way to correct that, and why is the codes not working.
Any instruction is highly appreciated, thanks a lot.