日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

用Javascript实现interface的类似功能

發布時間:2025/3/15 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 用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>

轉載于:https://www.cnblogs.com/lsgoodsun/archive/2007/05/22/756108.html

總結

以上是生活随笔為你收集整理的用Javascript实现interface的类似功能的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。