1 //simple rewriting of prototype objects:2 3 //a constructor person4 functionPerson () {5 6 }7 //rewrite a person's prototype8 //Assigning a person's prototype to a new object is the process we rewrite.9Person.prototype={Ten //for constructors If we don't write to him, the constructor is the constructor of object . OneConstructor:person,//Add constructor Properties Here's a bit of a problem because the constructor property is not enumerable and cannot be set here AName: "Zhang San", -Sayname:function(){ -Alert This. Name); the } - }; - - varP1 =NewPerson (); + alert (Person.prototype.constructor); - + /* A above we think the simulation overrides a prototype of a constructor at But there are a lot of problems. Constructors are not enumerable, and we cannot implement non-enumerable properties here. - - provide Object.defineproperty (object, property, configuration) in JS to implement some properties of setting properties - rewriting a prototype can be done as follows: - * */ - Object.defineproperty ( inPerson.prototype,//the object to configure -"Constructor",//constructor Builder for configuration objects to{//properties of the constructor +Enumerable:false,//constructor is not enumerable -Value:person//the value of the constructor is person the } * ); $ //The constructor is set to be non-enumerable by overriding the above method.Panax Notoginseng varP2 =NewPerson (); - for(attrinchp2) { the alert (attr); + } A the /* + Note: Due to the dynamic nature of the language - $ If you add a property or method to the prototype after instantiating the object, the instance object is actually a property and method that can be added after it is called $ after instantiating the prototype, actually the prototype of the instance still points to the original prototype object is not a new prototype object - */ - functionPerson () { the - }Wuyi varP1 =NewPerson (); thePerson.prototype.name= "haha"; -alert (p1.name);//haha because P1 's prototype reference call has been added before the property can be used Wu - varP2 =NewPerson (); AboutPerson.prototype = { $ Constructor:person, -Name: "Xixi" - }; -alert (p2.name);//haha, after the instance object changes the prototype of the constructor, the prototype of the instance object also points to the original A + varP3 =NewPerson (); thealert (p3.name);//Xixi Because this is an instance object after changing the constructor prototype
Prototype of JavaScript simple rewrite builder