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?
One: Create objects by "literal" way
Method: Writes the member information to {} and assigns a value to a variable, at which point the variable is an object
Gca
var person={"name": "ABC", "Age": 22,work:function () {Console.loh (1)}}
If the {} is empty, an empty object is created:
var person={}
Demo Code:
<script> var person={ name:"WQC", age :$, intro: function() {console.log (1)}}; Person.intro (); </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];Enrich member Information:
<script>var person={ name:"WQC", age :$, intro: function() { console.log (1); } } Person.class= 22; // Enrich member variables </script>
Second, create through the "constructor" mode
Method:
var person=new function name ();
For example: Var person=new object ();
<script> function person () { this. Name= "Xiaoming"; this. age=22; this. intro=function() { Console.log (2) } } var per=New person (); Per.intro (); </script>
Third, create through the object method.
var obj=New Object ()
Method: The object constructor is used to new objects, and then the member information is enriched. \
<script type= "Text/javascript" >2 var person = new Object (), 3 Person.name = "DONGJC"; 4 person.age = 32;5 person. introduce = function () {6 alert ("My name is" + THIS.name + ".) I ' m "+ this.age); 7 };8 person. Introduce (); 9 </script>
Fifth: Prototype Creation object pattern
function= ' Nike '== ' teacher 'function() {alert ( this. name);}; var New Person ();p erson1.sayname ();
Using prototypes to create objects, you can have all object instances share the properties and methods that it contains.
Sixth: Creating objects using Factory mode
functionvarnew== = function () { alert (this. Name); return o;} var = Createperson (' Nike ', Person1, ' teacher '); var person2 = Createperson (' Arvin ', ' student ');
When creating objects using Factory mode, we can all notice that in the Createperson function, an object is returned. Then we have no way of judging what type of object is returned. Then there is the second pattern of creating the object.
Seventh: Combining the constructor pattern with the prototype pattern
functionthis. Name ="This" = this. Job == function() {alert (this. name);};} var New Person (' Nike ', ' teacher ');
Several ways to organize JS object creation