//Test接口
var Person = E.createInterface('say', 'eat');
var Chinese = function() {};
Chinese.prototype.say = function() {
alert('說漢語')
}
Chinese.prototype.eat = function() {
alert('吃中餐')
}
E.implement(Chinese, Person);
//Test繼承
var Instrument = function(name, tone) {
this.name = name;
this.tone = tone
}
Instrument.prototype.play = function() {
alert(this.name + '的音色:' + this.tone);
};
var Guitar = function(name, tone) {
this.superclass.call(this, name, tone);
}
Guitar = E.extend(Guitar, Instrument);
var fingerGuitar = new Guitar('杉田健司', '高音甜中音穩低音狠 ');
fingerGuitar.play();
alert(fingerGuitar instanceof Guitar);
實現繼承和接口的工具類
/**
*
*/
E = {};
E.extend = function(sub, sup) {
//借用構造函數
sub.prototype = new sup();
//保留父類的構造函數,以便在子類構造函數中用調用,將父類變量綁定在this下
sub.prototype.superclass = sup;
//因爲重寫了構造函數所以重新指定constructor,以使instanceof表現正常
sub.prototype.constructor = sub;
//因爲已經將變量綁定到子類上,所以刪除原型上多餘的變量
return sub;
};
//實現類是否實現了所有接口的方法
E.implement = function() {
var sub = arguments[0];
for (var i = 1; i < arguments.length; i++) {
var sup = arguments[i];
try {
sup.implemented(sub);
} catch (e) {
throw new Error('no implements interface ' + sup);
}
}
};
E.factory = {};
//創建接口
E.createInterface = E.factory.createInterface = function(methods) {
var f = typeof arguments[0] === 'string';
var p = f ? arguments : arguments[0];
var len = p.length;
var Interface = function() {};
var _proto = Interface.prototype = {};
_proto.implemented = function(constructor) {
for (var i = 0; i < len; i++) {
var obj = new constructor();
if(!obj[p[i]]) {
throw new Error('no implements interface');
}
}
};
return new Interface();
};