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 .
Statement:The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn