[导入]用Javascript实现interface的类似功能
由于javascript是弱類型的語言,
參數不能限定類型,
所以提供一個方法isInstence(obj)來判斷此對象是否是實現這個接口的類型.
注意,在實現這個接口之后并不會把這個接口加入到Function 的原形鏈中.
(此功能支持同時實現多個接口)
<script language="javascript">
Function.prototype.exChain=new Array();
Function.prototype.implements=function(itf)
{
?
???? var innerObj=new this();
???? for(i in itf.abstruct)
???? {
????? if(itf.abstruct[i].constructor==Function)
????? {
?????? if(!innerObj[i])
?????? {
??????? throw new Error(9001,"請實現接口中的所有抽象函數。")
?????? }
????? }
???? }
???? this.exChain.push(itf.constructor);
???? this.exChain.push(this);
???? innerObj=null;
???? return this;
}
var Abstruct=function(){}
Function.prototype.isInstence=function(obj)
{
???? for (var i=0;i<obj.constructor.exChain.length;i++)
???? {
????? if(this==obj.constructor.exChain[i])
????? {
?????? return true;
????? }
???? }
???? if(this==obj.constructor)
???? {
????? return true;
???? }
???? return false;
}
/
InterfaceA=function()
{
???? this.abstruct=new Abstruct();
???? this.abstruct.show=function(){}
???? //this.abstruct.getMsg=function(){}
}
InterfaceB=function()
{
???? this.abstruct=new Abstruct();
???? this.abstruct.showB=new Function();
}
var ClassA=function()
{
???? this.show=function()
???? {
????? alert("ClassA");
???? }
???? this.showB=function()
???? {
????? alert("ClassA.showB")
???? }
?
}.implements(new InterfaceA()).implements(new InterfaceB())
var o1=new ClassA();
o1.show();
o1.showB();
alert(InterfaceA.isInstence(o1));
alert(InterfaceB.isInstence(o1));
alert(ClassA.isInstence(o1));
?
var ClassB = function()
{
?
}
alert(ClassB.isInstence(o1));
</script>
suiqirui 2007-05-22 20:06 發表評論
文章來源:http://www.cnblogs.com/suiqirui19872005/archive/2007/05/22/756108.html
轉載于:https://www.cnblogs.com/QiRuiNet-helloworld/archive/2007/06/19/789096.html
總結
以上是生活随笔為你收集整理的[导入]用Javascript实现interface的类似功能的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 高品质生活
- 下一篇: asp.net2.0导出pdf文件完美解