// The prototype method creates the object's properties and methods to achieve the purpose of sharing function Box () {}; // There 's nothing inside, if there is an instance property and method Box.prototype.name= ' Tianwei '; Box.prototype.age= ' + '; Box.prototype.run=function() { returnthis. name+ . Age;}; var box1=New Box ();d ocument.write (box1.name);
Instance properties are not shared, prototype properties are shared, priority access to instance properties
//delete attributes: Delete Box1.name; Delete box.prototype.name;//Determines whether the attribute is in the instance: Box1.hasownproperty (' name '); // returns true whenever this property is available in Box1;
// The prototype method creates the object's properties and methods to achieve the purpose of sharing function Box () {}; // There 's nothing inside, if there is an instance property and method Box.prototype={ constructor:box, name:' Tianwei ', age :' + ', run: function () { returnthis. name+the. Age; }} var box1=New Box ();d ocument.write (box1.constructor);
var box= [1,2,3,2,10,3];d ocument.write (Box.sort ()); /* Array.prototype.sort; */ alert (STRING.PROTOTYPE.SUBSTR); String.prototype.addString=function() { returnthis + ' add success ';}; var box= ' 4343 '; alert (box.addstring ());
Requires a separate section to use the constructor
Need to share parts using prototype mode
//Composition Building function + prototypefunctionBox (name,age) {//need a stand -alone section This. name=name; This. age=Age ; This. family=[' 1 ', ' 2 ', ' 3 '];} Box.prototype={//Share partConstructor:box, run:function(){ return This. name+ This. Age; }}varbox1=NewBox (' Tian ', 100); Box1.family.push (' 4 '); alert (box1.family);varBox2=NewBox (' Wei ', 200); alert (box2.family);
Wrap the above together and use
Dynamic Prototyping Mode
//Composition Building function + prototypefunctionBox (name, age) {//need a stand -alone section This. Name =name; This. Age =Age ; This. Family = [' 1 ', ' 2 ', ' 3 ']; //prototypes only need to be initialized once if(typeof This. Run! = ' function ') {Box.prototype.run=function() { return This. Name + This. Age; } }}varBox1 =NewBox (' AAA ', 111); alert (Box1.run ());varBox2 =NewBox (' BBB ', 222); alert (Box2.run ());
JS prototype prototype Attribute usage example