2. Prototype method
/**
* Person class: defines a person, has an attribute name, and a getName method
*/
function Person(){}
Person.prototype.name = "jack";
Person.prototype.getName = function() { return this.name;}
Hang the attributes (fields) and methods of the class on the prototype.
Create a few objects to test:
var p1 = new Person();
var p2 = new Person();
console.log(p1.getName());//jack
console.log(p2.getName()) ;//jack
It can be seen that the output is all jack, so the disadvantage of the prototype method is that the object instance cannot be constructed through parameters (generally the attributes of each object are different), and the advantages are all Object instances all share the getName method (compared to the constructor method), which does not cause memory waste .