Use JavaScript to implement similar interface functions

Source: Internet
Author: User

Because Javascript is a weak language,

The parameter cannot specify the type,

Therefore, a method isinstence (OBJ) is provided to determine whether the object is of the type that implements this interface.

Note that this interface will not be added to the original function chain after implementation.

(This function supports multiple interfaces at the same time)
<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, "implement all Abstract Functions in the interface. ")
}
}
}
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>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.