ECMAScript5中如何定义接口
接口和抽象类是静态面向对象编程语言的概念,如何在ES5中模拟接口和抽象类,这需要程序员有意识的养成良好的编码习惯,下面我们一起来展示一下接口如何定义:接口的定义(模拟发布/订阅模式下的主题接口)
var Subject=(function(){
function Subject()
{
//禁止调用该函数
throw {
name:"Error",
message:"接口不能调用和实例化"
};
}
//抽象方法
Subject.prototype.notify=function(data){throw new Error("抽象方法不能调用");};
Subject.prototype.subscribe=function(observe){throw new Error("抽象方法不能调用");};
Subject.prototype.unsubscribe=function(guid){throw new Error("抽象方法不能调用");};
return Subject;
})();接口实现
var SubjectHelper=(function(){
function SubjectHelper()
{
this.observers={};
this.guid=0;
}
//实现接口原型方法
SubjectHelper.prototype=Object.create(Subject.prototype);
SubjectHelper.prototype.constructor=SubjectHelper;
//实现抽象方法
SubjectHelper.prototype.notify=function(data){
for(var key in this.observers)
{
var observer=this.observers[key];
if(typeof observer==="function")
{
observer.call(this,data);
}
}
};
SubjectHelper.prototype.subscribe=function(observer){
this.observers[this.guid++]=observer;
return this.guid-1;
};
SubjectHelper.prototype.unsubscribe=function(guid){
delete this.observers[guid];
};
return SubjectHelper;
})();