JavaScript Object __java

Source: Internet
Author: User
Tags class definition

1. Constructor mode

Simulates "class" with a constructor to refer to the instance object internally using the This keyword.

Basic syntax:

function class name () {
this. property name;//Public property
var property name;//Private property
/general definition of the public properties of the class and public methods are to use the this/
Defining the public functions of a class
this. function name =function () {
.....
}
To define a private function of a class
function functions name () {
......
}
}

Example:

/* Define the exposed properties of a person class/function person (_name,_age,_salary) {//person class, and the exposed properties of the class are defined by: "this. Property name" This.name=
        _name; The private property of the person class, the private property of the class is defined by: "var attribute name" var age=_age;//private property var salary=_salary;//private Property/* Define private attribute Age's pair
        External public access Method */this.setage = function (intAge) {age = IntAge;
        }/* Defines the private attribute age's external access method/This.getage = function () {return age;
        }//Defines the public method (privileged method) of the person class, and the method of exposing the class is defined by: "This.functionname=function () {...}" This.
        Show=function () {Document.writeln ("private property that accesses the class in the public method is allowed, age=" +age+ "\ T" + "salary=" +salary); access to private properties of the class in the public method is allowed
            }//Public method This.publicmethod = function () {Document.writeln ("Private method of accessing class in public method is allowed"); Privatefn ();//The Private method that invokes the class in the public Method privateFn2 ()//The private method that invokes the class in the public method}/* Defines the private of the person class There are methods (internal methods), and the private methods of the class are defined by: "function functionname () {...}", or Var functionname=function () {...}
        /function Privatefn () {Document.writeln ("I am the private function of the person class Privatefn");
        var privatefn2=function () {Document.writeln ("I am the private function of the person class privateFn2"); }
    }

Test Person class

var p1 = new Person ("aloof wolf", 24,2300);
    var p2 = new Person ("White Tiger Emperor", 24,2300);
    document.write ("<pre>"); Document.writeln (The result of the "P1 instanceof person is:" + (P1 instanceof person));//p1 is an instance of the person class, and the result is true Document.writeln ("P2 The result of instanceof person is: "+ (p2 instanceof person);//p2 is an instance of the person class, and the result is true//if the content on either side is an object or a function property of an object, compare the memory address for Equality Docum
    Ent.writeln ("Compare the memory address for equality" when the content on either side of = = is the object or the function property of the object);
    Document.writeln ("Compare the memory addresses of the show methods of the P1 and P2 these two objects: the result of p1.show== P2.show is:" + (P1.show = p2.show));//false Document.writeln ("p1.show = = P2.show Result:" + (p1.show = = p2.show) + ", which proves that the P1 object and the P2 object are not sharing a show method, there are 2 code in memory Show method,
    stored in two memory areas ");
    Document.writeln ("Name is the public property defined by the person class, you can use the object of the class to directly access the public properties of the class"); Document.writeln ("p1.name=" +p1.name);//Access public properties, which are normal access Document.writeln ("Age and salary are private attributes defined by the person class,
    Can not use the object of the class to directly access the class private properties, this is not accessible, the result is undefined "); Document.writeln ("p1.age=" +p1.age+ "," + "p1.salary=" +p1.salary)//cannot use the object of the class to directly access the class private property, which is not accessible, the result is undefined p1.show ();//Calling public functions of a class, this time the permitted P1.publicmethod ()//Call the public function of the class, this time the allowed P1.setage (24);//Use the publicly method Setage method to assign a value to the private property age Document.writeln ("use pub The Lic method getage the value of the private property Age, p1.getage () = "+p1.getage ());//Use the Getage method to get the value of the private property Age//document.writeln (" P1.privatefn ():
    "+p1.privatefn () +" &nbsp;p1.privatefn2 (): "+p1.privatefn2 ());//cannot use the object of the class to invoke the private method of the class, this will be an error" object does not support this property or method document.write ("</pre>");

Test results:

The advantage of this approach is that you can construct different object instances based on parameters, each object's properties are generally not the same, the disadvantage is to construct each instance object, methods can not be shared, the person class definition of those methods, P1 object has a copy, p2 also have a copy, Then in memory we have to open two of memory space to store P1 methods and P2 methods, thus creating a waste of memory. For different instance objects of a class, the properties of these objects are generally not the same, but the method is the same, so saving memory is to place the method in a piece of memory, and then each instance object takes the method out of the block of memory.

2. Prototype mode

It is necessary to note that using a prototype to write a JavaScript class is not possible to add private and private methods to the class, and that the properties and methods added using the stereotype are public.

Writing a:

/* Define a person class */function person (_name,_age,_weight,_height) {this.init (_name,_age,_weight,_height);
    /* Use a prototype to define the public property of the person class: Name,age,weight,height, the attributes added by using a prototype are public/Person.prototype.name;
    Person.prototype.age;
    Person.prototype.weight;
    Person.prototype.height; /* Use a prototype to add the public method to the person class, and the method to be added using the prototype is public////* Use the prototype to add the Init method to the person class/* Person.prototype.init = function (_ Name,_age,_weight,_height) {if (_name!= undefined && _age!=undefined && _weight!=undefined && Amp
            _height!=undefined) {this.name = _name;
            This.age = _age;
            This.weight=_weight;
            This.height=_height; Document.writeln ("This.name=" +this.name+ ", this.age=" +this.age+ ", this.weight=" +this.weight+ ", this.height=" +
        This.height);
    }/* Use a prototype to add a show method to the person class */Person.prototype.show = function () {Document.writeln ("show Methods"); }

Test Person class

document.write ("<pre>");
    var p1 = new Person ("aloof, pale Wolf", 24,115,160);
    var p2 = new Person ("White Tiger Emperor", 25,120,170);
    var p3 = new person (); P3.init ("Xuan Tian Evil Emperor", 26,130,180);//Call public method init initialize P3 object Document.writeln ("P1 instanceof person results are:" + (P1 instanceof );//p1 is an instance of the person class, and the result is true Document.writeln ("P2 instanceof person's result is:" + (P2 instanceof person));
    P2 is an instance of the person class, and the result is true Document.writeln ("P3 instanceof person's result is:" + (p3 instanceof person));//p3 is an instance of the person class, and the result is true
    When the content on either side of the = = is the object or the function property of the object, compare the memory address for Equality Document.writeln ("Compare the memory address for equality when the content on both sides is the object or the function property of the object");
    Document.writeln ("Compare the memory addresses of the show methods of the P1 and P2 these two objects: the result of the P1.show = = P2.show is:" + (P1.show = p2.show));//true Document.writeln ("p1.show = = P2.show result is:" + (p1.show = = p2.show) + ", which proves that the P1 object and the P2 object share a Show method, in the memory shows the method's code only one copy, An area stored in memory ");//true Document.writeln (" P1.name= "+p1.name+, p1.age=" +p1.age+ ", p1.weight=" +p1.weight+ ", p1.height=" +p1.height)//access to the public property, which is a normal access to the Document.writeln ("P2.name=" +p2.name+, p2.Age= "+p2.age+", p2.weight= "+p2.weight+", p2.height= "+p2.height";//Access public property, which is a normal access to the P3.name= "destroy the World"; re-assign values to public properties Document.writeln ("p3.name=" +p3.name);//Access public property, this is a normal access to the p1.show ()//Call class's common function, this time allowed document.write ("</pre>" );

Test results:

Writing two:
Using prototypes to define the public and public methods of a class is more elegant, and I personally recommend it in a way that looks more comfortable.

/* Define class person2*/
    function Person2 () {

    }

    * * Use prototypes to define the public property and public method for a class more elegant writing/
    Person2.prototype = {
        name: "",//public Property
        Age:0,//public Property
        Weight:0,//public Property
        Height:0,//public Property
        /*public Method * *
        init:function (_name,_age,_weight,_height) {
            this.name = _name;
            This.age = _age;
            This.weight=_weight;
            This.height=_height;
            Document.writeln ("This.name=" +this.name+ ", this.age=" +this.age+ ", this.weight=" +this.weight+ ", this.height=" + this.height);
        },
        /*public method *
        /Show:function () {
            Document.writeln ("Show Methods");
        }
    ;

Test code:

document.write ("<pre>");
    var p2_1 = new Person2 ();
    var p2_2 = new Person2 ();
    P2_1.init ("Aloof Wolf", 24,115,160);
    P2_2.init ("White Tiger Emperor", 25,120,170); Document.writeln ("P2_1.name=" +p2_1.name+), p2_1.age= "+p2_1.age+", p2_1.weight= "+p2_1.weight+", p2_1.height= "+p2_" 1.height)//access to the public property, this is a normal access to the Document.writeln ("P2_2.name=" +p2_2.name+, p2_2.age= "+p2_2.age+", p2_2.weight= "+p2_" 2.weight+ ", p2_2.height=" +p2_2.height)//Access public property, which is a normal access Document.writeln ("P2_1 instanceof The result of Person2:" + (P2_1 instanceof Person2));//p2_1 is an instance of the Person2 class and the result is true Document.writeln ("p2_2 instanceof The result is:" + (Person2 p2_2 Person2);//p2_2 is an instance of the Person2 class, and the result is true//when the content on either side of the = = is an object or a function property of the object, compare the memory address for Equality document.writeln ("when = =
    Compare the memory address if the content on either side is an object or a function property of the object; Document.writeln ("Compares the memory addresses of the Init methods of the P2_1 and p2_2 the two objects: the result of P2_1.init = = P2_2.init is:" + (P2_1.init = P2_2.init));//true P2 _1.name= "The Evil of the World";//Reassign the Public property Document.writeln ("P2_1.name=" +p2_1.name);//access the public property, which is a normal access to the p2_1.show ();//Call the class's common function. This timeXu's document.write ("</pre>"); 

Test results:

Advantages of Prototyping: All object instances share the methods defined in the class, so that no memory waste is caused. Disadvantage, first, you cannot define private and private methods for a class, and second, you need to write an additional initialization object when creating an object that initializes the property of the object.

3. Construction function + prototype

Both constructors and prototypes have their own advantages and disadvantages, so you can combine the two methods to define the properties of the class (public property, private property) by using a constructor to define the method of the class (public method). Complementary, this has a third way of writing.

/* Define a person class/function person (_name,_age,_salary) {//define the public and private properties of the class and private methods within the person class//p
        Erson the exposed property of the class, the exposed property of the class is defined by: "this. property name" This.name=_name;
        The private property of the person class, the private property of the class is defined by the "var attribute name" Var age=_age;//private property, which can only be used within the class using the var salary=_salary;//private property, only within the class /* Defines the private method of the person class (internal method), which can only be defined by using the class's private method within the class: "function functionname () {...}", or Var functio
        Nname=function () {...}
            * * Function Privatefn () {document.write ("<pre>");
            Document.writeln ("I am the private attribute of the person class age, can only be used within the person class, initialize the age=" +age);
            Document.writeln ("I am a private function of the person class Privatefn, can only be used within the person class");
        document.write ("</pre>");
            var privatefn2=function () {document.write ("<pre>");
            Document.writeln ("I am the private property of the person class salary, can only be used within the person class, initialize salary=" +salary);
            Document.writeln ("I am a private function of the person class privateFn2, can only be used within the person class"); DOcument.write ("</pre>"); Privatefn ()///calling private methods inside the person class PRIVATEFN2 ()///calling private methods inside the person class}////using a method defined by the prototype prototype (public
            method is not accessible to the private and private methods of the class//the party public method that defines the person class using the prototype stereotype person.prototype={setname:function (_name) {
            THIS.name = _name; Privatefn ();//cannot invoke the private method Privatefn () defined by the person class to complain: Missing object}, Getname:function () {return this.name
        ;
        }, Show:function () {Document.writeln ("public method Show");
        },//Public method Publicmethod:function () {Document.writeln ("public Method Publicmethod"); }
    };

Test code:

var p1 = new Person ("aloof wolf", 24,2300);
    var p2 = new Person ("White Tiger Emperor", 25,3000);
    document.write ("<pre>"); Document.writeln (The result of the "P1 instanceof person is:" + (P1 instanceof person));//p1 is an instance of the person class, and the result is true Document.writeln ("P2 The result of instanceof person is: "+ (p2 instanceof person);//p2 is an instance of the person class, and the result is true//if the content on either side is an object or a function property of an object, compare the memory address for Equality Docum
    Ent.writeln ("Compare the memory address for equality" when the content on either side of = = is the object or the function property of the object);
    Document.writeln ("Compare the memory addresses of the show methods of the P1 and P2 these two objects: the result of p1.show== P2.show is:" + (P1.show = p2.show));//true Document.writeln ("p1.show = = P2.show result is:" + (p1.show = = p2.show) + ", which proves that P1 object and P2 object share a show method, in memory there are 1 code in the Show method,
    Stored in 1 block memory area ");
    Document.writeln ("Name is the public property defined by the person class, you can use the object of the class to directly access the public properties of the class"); Document.writeln ("p1.name=" +p1.name);//Access public properties, which are normal access Document.writeln ("Age and salary are private attributes defined by the person class,
    Can not use the object of the class to directly access the class private properties, this is not accessible, the result is undefined "); Document.writeln ("p1.age=" +p1.age+ "," + "p1.salary=" +p1.salary)//cannot use the object of the class to directly access the class private property, which is not accessible, the result is undefined p1.show ();//Call the class's public function, this timeThe allowed P1.publicmethod ();//Call the public function of the class, this time allowed P1.setname ("Hyun-Tian Evil Emperor"); the public function of the calling class is set to the Name property to be assigned a value Document.writeln ("P1.getname
    = "+p1.getname ()); Document.writeln ("P1.privatefn ():" +p1.privatefn () + "&nbsp;p1.privatefn2 ():" +p1.privatefn2 ()); You cannot use the object of a class to invoke the private method of a class, which can be an error "object does not support this property or method document.write (" </pre> ");

Run Result:

The Third way, through the combination of the first two, is to achieve a more ideal writing, you can construct the object instance through the argument, the object instance share the same method does not cause memory waste. The third way is most used in development, and I am writing JavaScript classes in this way myself.

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.