SoFunction
Updated on 2025-04-10

JavaScript writing method three

Take the advantages of the first two:
a. Use constructor to define class attributes (fields)
b. Use prototype to define the method of class.
There is a third way. This method seems to be adopted by many people.
3. Comprehensive constructor/prototype
Copy the codeThe code is as follows:

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

In this way, people with different names can be constructed through constructors, and object instances also share the getName method, without causing memory waste.
But it seems that such a code style still seems to be not as compact as Java classes, including properties, constructor methods (functions), and methods in braces.
Copy the codeThe code is as follows:

public class Person {
//Properties (fields)
String name;
//Constructor method (function)
Person(String name) {
= name;
}
//method
String getName() {
return ;
}
}

In order to make the js code more compact, move the method code hanging in prototype into the braces of function Person.
Copy the codeThe code is as follows:

function Person(name) {
= name;
= function() {
return ;
}
}

It seems very magical, and I can still write like this! Verify
Copy the codeThe code is as follows:

var p1 = new Person("Jack");
var p2 = new Person("Tom");
(());//Jack
(());//Tom

There is no error, and the console outputs correctly. This is the way it can be written, haha.
Well, it seems perfect.
a. Object instance can be constructed by passing parameters
b. The same method is shared by the object instances without causing memory waste.
c. The code style is also relatively compact
But every time a new object is executed
= function() {
return ;
}
Cause unnecessary repetitions. Because the getName method needs to be executed once on the prototype. Just make a little modification:
Copy the codeThe code is as follows:

function Person(name) {
= name;
if(Person._init==undefined) {
alert("I only execute once!");
= function() {
return ;
}
Person._init = 1;
}
}

new two objects,
Copy the codeThe code is as follows:

var p1 = new Person("Andy");//The first time new will pop up 'I only execute it once! '
var p2 = new Person("Lily");//The new object will not be executed in the future