Learn to use Class in Javascript

来源:互联网 发布:java基本数据类型存储 编辑:程序博客网 时间:2024/06/15 06:38

<script language="javascript" type="text/javascript">
// <!CDATA[
// use Array
var gsArray =  new Array('a','b','c','d');

function Button1_onclick() {
    var a ="";
//    for(var i=0;i<gsArray.length;i++)
//        a += gsArray[i];
//    document.write(a);

    // create object1
    var person = new Person("George","Male",25);
    person.SetEmail("geforcesong@gmail.com");
    person.Show();
    person.Trim();
   
    // create object2
    var jenny = new Person("Jenny","Female",26);
    jenny.Email = "greenfish_2005@hotmail.com";
    jenny.Show();
   
    var str = new String('aaaaaaaaaa')
    str.AAA();
}

function Person(Name,Sex,Age)
{
    // the general function
    function Show()
    {
        var message = "";
        // this.GetMessage(), 这样的调用方法是必须的,如果不加this的话就代表不是当前对象,会得到错误的结果。
        message = this.GetMessage();
        alert(message);
    }
   
    // the member function which contains a parameter
    function SetEmail(el)
    {
        this.Email = el;
    }
   
    // the function which returns a string
    function GetMessage()
    {
        var message = "";
        message = this.Name + "<br/>" + this.Sex + "<br/>" + this.Age + "<br />" + this.Email;
        return message;
    }
   
    // it is another way of registering your function.
    Person.prototype.Trim = function()
    {
        alert("Trim" + this.Name);
    }
   
    // properties
    this.Name = Name;
    this.Sex = Sex;
    this.Age = Age;
    this.Email = null;
    // member functions
    // if the function will be call through object, it must be registed here as follows,
    this.Show = Show;
    this.SetEmail = SetEmail;
    this.GetMessage = GetMessage;
}

// it can extend javascript class,e.g the code follows extended the class String. It make it has anoter extra funcation AAA.
String.prototype.AAA = function()
{
    alert(this);
}
// ]]>
</script>