Learn to use Class in Javascript

    技术2022-05-11  69

    <script language="javascript" type="text/javascript">// <!CDATA[// use Arrayvar 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> 


    最新回复(0)