Mode
1 //constructor + prototype model2 functionBox (name,age) {//maintain independent use of constructors3 This. name=name;4 This. age=Age ;5 This. family=[' elder brother ', ' elder sister ', ' brother '];6 7 }8 9box.prototype={//Maintaining a shared prototype modelTen Constructor:box, OneRunfunction(){ A return This. Name + This. Age + This. Family; - } - } the - varBox1 =NewBox (' Lee ', 100); - //alert (Box1.run ()); -Box1.family.push (' sister ')); + alert (box1.family); - + varBox2 =NewBox (' Jack ', 200); A //alert (Box2.run ()); atalert (box2.family);//reference types do not use prototypes, so there is no sharing
Dynamic prototypes
1 //A dynamic prototype model that encapsulates a prototype into a prototype that is initialized once per run2 functionBox (name,age) {3 This. name=name;4 This. age=Age ;5 This. family=[' elder brother ', ' elder sister ', ' brother '];6 7 //alert ("Start of prototype initialization");8 //Box.prototype.run = function () {9 //return this.name + this.age + this.family;Ten // } One //alert ("Initialization end of prototype"); A - if(typeof This. Run! = ' function ') {//determines whether the run exists, that is, whether it has been initialized -Alert ("Start of prototype initialization"); theBox.prototype.run =function(){ - return This. Name + This. Age + This. Family; - } -Alert ("Initialization end of prototype"); + } - } + A varBox1 =NewBox (' Lee ', 100); at alert (Box1.run ()); - - varBox2 =NewBox (' Jack ', 200); -Alert (Box2.run ());
Factory model
1 Factory mode2 functionObject (name,age) {3 varobj =NewObject ();4Obj.name =name;5Obj.age =Age ;6Obj.run =function(){7 8 9 }Ten returnobj; One}
Parasitic structural function model
1 //Parasitic constructor Mode2 functionBox (name,age) {3 varobj =NewObject ();4Obj.name =name;5Obj.age =Age ;6Obj.run =function(){7 returnName +Age ;8 }9 returnobj;Ten}
Secure constructor Model
1 //Secure constructor, function body cannot use this, instantiation cannot be used with new2 functionBox (name,age) {3 varobj =NewObject ();4Obj.name =name;5Obj.age =Age ;6Obj.run =function(){7 returnName +Age ;8 }9 returnobj;Ten } One varBox1 = Box (' Lee ', 100); AAlert (Box1.run ());
JavaScript Object-oriented and prototype