JS Defining classes and objects
1. Factory mode
<script type= "Text/javascript" >
function CreateObject (name) {
var p = new Object ();
P.name=name;
P.say = function () {alert (p.name+ ' FF ');}
return p;
}
var P1 = CreateObject ("P1");
var P2 = CreateObject ("P2");
Alert (p1.name+ "" +p2.name);
P1.say ();p 2.say ();
alert (P1.say==p2.say); False
</script>
Problem: Each object is created by a new object, wasting resources
2. How to construct a function
<script type= "Text/javascript" >
function person (name) {
THIS.name = name;
This.say = function () {
Alert ("I AM" +this.name);
}
}
var p1 = new Person ("Wang");
var p2 = new Person ("Li");
P1.say ();
P2.say ();
alert (P1.say==p2.say); False
</script>
Problem: Creating objects is more understandable than factory methods. As with factory methods, each object has its own method, wasting resources.
3. Prototype mode
function person () {}
Person.prototype.name= "";
Person.prototype.say=function () {
Alert ("I AM" +this.name);
}
var p1=new person ();
var p2=new person ();
alert (P1.say==p2.say);//true
Problem: Cannot pass parameters in the constructor method, all objects share properties.
Advantages: Object Sharing method, saving resources.
4. Construction Method + prototype mode
function person (name) {
This.name=name;
}
Person.prototype.say=function () {
Alert ("I AM" +this.name);
}
var p1=new person ("Wang");
var p2=new person ("Li");
P1.say ();
P2.say ();
alert (P1.say==p2.say);//true
Pros: Resolves the previously mentioned issues
Problem: Encapsulation is not perfect.
5. Dynamic Prototyping Mode
function person (name) {
This.name=name;
if (person.prototype.say==undefined) {
Person.prototype.say=function () {
Alert ("I AM" +this.name);
}
}
}
var p1=new person ("Wang");
var p2=new person ("Li");
P1.say ();
P2.say ();
alert (P1.say==p2.say);//true
Conclusion: a perfect solution.
6. Creation of Objects--json
var person={};
var girl={
Name: "Miss Wang",
AGE:20,
Show=function () {
Alert ("My name is" +this.name);
}
}
JS Defining classes and objects