SoFunction
Updated on 2025-04-10

JavaScript writing method two

2. Prototype method
Copy the codeThe code is as follows:

/**
* Person class: defines a person, has a property name, and a getName method
*/
function Person(){}
= "jack";
= function() { return ;}

Hang the properties (fields) and methods of the class on the prototype.

Create a few objects to test:
Copy the codeThe code is as follows:

var p1 = new Person();
var p2 = new Person();
(());//jack
(());//jack

It can be seen that the output is jack, so the prototype method isThe disadvantage is that the object instance cannot be constructed through parameters(Generally, the properties of each object are different),The advantage is that all object instances share the getName method (relative to the constructor method), and there is no memory waste.