Javascript implements encapsulation similar to C # classes

Source: Internet
Author: User

I have not studied Javascript deeply. Although I have many C # class libraries of my own, I don't have a js class library of my own. I have been using it all the time and try again. In the future, we will encapsulate common js methods like C # classes.

JsClass. js File

// Define a class
Function _ HY_JsClass (){}

// Define the attributes of a class
_ HY_JsClass.prototype = {
P1: 0,
P2: {a: 0, B: 1}
}

// Define the Class Method
_ HY_JsClass.prototype.myMethod = function (param1, param2 ){
Return param1 + param2;
}

// Create a class instance
Var _ HY_JsClass = new _ HY_JsClass ();

/*
// Call Method
_ HY_JsClass.myMethod (1, 2 );

// Set attributes
_ HY_JsClass.p1 = 100;
*/
JsClass.htm File

<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head>
<Title> Javascript implements encapsulation like C # class -bkjia.com </title>
<Script type = "text/javascript" src = "js/JsClass. js"> </script>
<Script type = "text/javascript">
// Use the class library to introduce the js file. Call the js method directly using the Instance name, just like the static method in C.
Function f (){
Alert (_ HY_JsClass.myMethod (1, 2); // Instance name. Method (parameter list ..);
_ HY_JsClass.p1 = 1; // Instance name. Attribute
Alert (_ HY_JsClass.p1 );
}
</Script>
</Head>
<Body>
<Input type = "button" value = "OK" onclick = "f ();"/>
</Body>
</Html>

Related Article

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.