JavaScript is a "prototype-based object-oriented language" that is very much different from Java and cannot be created by classes. So, how do you create an object, since it is a polygon object?
First, created by the "literal" way.
Method: Writes the member information to {} and assigns a value to a variable, at which point the variable is an object.
For example:
var person = (name: ' DONGJC ', work:function
If the {} is empty, an empty object is created:
var// Create empty object
Demo Code:
1 <script type= "Text/javascript" >2var person = {3 Name: " DONGJC ",4 age:32,5 functionthis this . Age); }6}; 7 Person . Introduce (); 8 </script>
We can also enrich the members information for the object.Object. member name = value;Object [member name] = value;You can also get member information for an object.Object. Name of the member;Object [member name];
1 <script type= "Text/javascript" >2 var person = {3 Name: "DONGJC",4 age:32,5 function This the. Age); }6}; 7 person.worker = ' coding '; Enrich member Information 8 </script>
Second, create through the "constructor" mode.
Method:
varnew function name ();
This is fundamentally different from creating objects from a class. When you create an object from this method, the function is automatically executed. This is similar to when PHP automatically calls the constructor by creating a pair of images, so the method is called creating the object through the constructor.
1<script type= "Text/javascript" >2 functionPerson () {3 This. Name = "DONGJC";//set a default member with the This keyword4 varWorker = ' coding ';//without the This keyword, after the object is created, the variable is non-member5 This. Age = 32;6 This. introduce =function () {7Alert ("My name is" + This. Name + ". I ' m "+ This. age);8 };9Alert ("My name is" + This. Name + ". I ' m "+ This. age);Ten }; One varperson =NewPerson (); A Person . Introduce (); -</script>
This code jumps out of the dialog box two times, because the object is created automatically by the function.
Note: Use of the This keyword. This is similar to the words in PHP, referring to the object that called the function, which refers to the person.
Third, create through the object method.
Method: The object constructor is used to new objects, and then the member information is enriched.
var obj = new Object ();
Instance code:
1<script type= "Text/javascript" >2 varperson =NewObject ();3Person.name = "DONGJC";4Person.age = 32;5Person. introduce =function () {6Alert ("My name is" + This. Name + ". I ' m "+ This. age);7 };8 Person . Introduce ();9</script>
JavaScript three ways to create objects