3. literal
In order for properties and methods to embody the encapsulated effect well, and to reduce the creation of unnecessary input prototypes, you can use literals.
The function Box () {} //uses the literal method to create the prototype object, where {} is the object, Object,new object is the equivalent of {} box.prototype={ name: ' Link ', age:23, run:function () { return this.name+this.age+ ' running ... ' } }; var box=new box (); Alert (Box.run ());
Using constructors to create prototype objects and to create objects using literals is basically the same as using, but there are some differences,
The way the literal is created uses the constructor property not to point to the instance, but to object, and the construction is created in the opposite direction.
creating objects by literal volume
The function Box () {} //uses the literal method to create the prototype object, where {} is the object, Object,new object is the equivalent of {} box.prototype={ name: ' Link ', age:23, run:function () { return this.name+this.age+ ' running ... ' } }; var box=new box (); Alert (Box.run ()); Alert (Box.constructor) //Is the object method, because {} is the objects, Object,new object is the equivalent of {}
constructor to create a prototype object
function Box () {} //constructor function body inside is nothing, if there is, it is called instance property, instance method. box.prototype.name= ' link '; Box.prototype.age= ' "; Box.prototype.run=function () { return this.name+this.age+ "Running ... " } var box=new box (); alert (box.constructor);//Is the box method.
If the literal wants the object conversion box can be used
The function Box () {} //uses the literal method to create the prototype object, where {} is the object, and the Object,new object is the equivalent of {} box.prototype={ constructor: box, //Direct force pointing to box name: ' Link ', age:23, run:function () { return this.name+this.age+ ' running ... ' } }; var box=new box (); Alert (Box.run ()); Alert (Box.constructor) //Is the box method.
Prototype objects can be used not only in the case of custom objects, but also in ECMAScript built-in reference types, and the built-in reference types themselves use prototypes.
Array sort var lis=[1,2,15,5,55,33,0] alert (Lis.sort ()) //view sort is not a method in the array prototype object alert ( Array.prototype.sort) alert (String.prototype.substring) //Add New method string.prototype.addstring= function () { return this+ ' new method '; } var box= ' link ' //Output link New method document.write (box.addstring ())
PS: Although it is convenient to add methods to native built-in reference types, we do not recommend this because it can lead to naming conflicts and is detrimental to the maintainability of the code.
JavaScript faces the object. Third article