Cover the prototype
//Prisoner example//1. Define the prototype object var proto = { sentence : 4, //Year of imprisonment probation: 2 //Year of probation}; //2. Define the constructor of the prototype object var Prisoner = function(name, id) { this.name = name; this.id = id; }; //3. Associate the constructor to the prototype Prisoner.prototype = proto; //4. Instantiate the object - instantiate the object var makePrisoner = function(name, id) { //Use factory function to power the object principal var prisoner = Object.create( proto ); prisoner.name = name; prisoner.id = id; return prisoner; }; var firstPrisoner = makePrisoner( 'Joe', '12A' ); //firstPrisoner.sentence cannot find the sentence attribute in the firstPrisoner object, //So find the prototype of the object and find both of these output 4 console.log( firstPrisoner.sentence ); console.log( firstPrisoner.__proto__.sentence ); //Set the sentence attribute of the object to 10 firstPrisoner.sentence = 10; //outputs 10 //Confirm that the property value on the object has been set to 10 console.log( firstPrisoner.sentence ); //But the prototype of the object has not changed, and the value is still 4 console.log( firstPrisoner.__proto__.sentence ); //In order to return the obtained attribute to the value of the prototype, delete the attribute from the object delete firstPrisoner.sentence; //Next, the JavaScript engine cannot find the attribute on the object, // You must go back to find the prototype chain and find the attribute on the prototype object// Both of these output 4 console.log( firstPrisoner.sentence ); console.log( firstPrisoner.__proto__.sentence );ubuntu terminal node output
xxh@xxh-E440:~/workspace$ node t6 4 4 10 4 4 4
So what happens if the property value of the prototype object is changed? I know you're thinking.
The above brief discussion on JavaScript overlay prototypes and changing prototypes is all the content I have shared with you. I hope you can give you a reference and I hope you can support Wulin.com more.