varProto =""; function person (name, age, job) { This. Name =name; This. Age =Age ; This. Job =job; if(typeof This. sayname! ='function') { //You cannot create a prototype object with literal literals here .//Person.prototype.sayname = function () {//console.log ("name =" + THIS.name); // };Proto = Person.prototype;//prototype object without literal rewriting//If you use literals to create prototype objectsPerson.prototype ={sayname:function () {Console.log ("Name:"+ This. Name); }} console.log (Proto= = Person.prototype)//False indicates that the person prototype object has been rewritten to change } } varperson =NewPerson ("Jack", -,'Programmer'); Console.log (person.__proto__= = Proto);//True The __proto__ of the instance object points to the original prototype object, rather than to the prototype object being overridden by the literalPerson.sayname ();//undefined method for no new prototype object
If you have already created an instance and then re-use the literal to rewrite the prototype , you will cut off the connection between the existing instance and the new prototype, as in the following words:
function Person () {}; varProto =Person.prototype; varperson =NewPerson ; //instance object in front Person.prototype={name:"Jack", Sayname:function () {Console.log ("Name:"+ This. Name); }} console.log (Person.prototype.isPrototypeOf (person)); //False The new prototype is not on the person object prototype chainConsole.log (proto.isprototypeof (person));//True The original prototype object is on the person object prototype chain
If you want to implement adding a method to an instance object that you have already created, you can write:
Function Person () {} varnew person (); Instance object in front of 'Jack'; = function () { Console.log (this. Name); } Person.sayname (); // Jack
This is not to re-declare a prototype object, but to extend the original prototype object .
"JavaScript" dynamic prototype Pattern Creation Object | | Why can't I create a prototype object in literal quantities?