There is no concept of class in the EMCA262 specification. New in js just makes it look more like c and java. The writing classes mentioned here are just writing js code style.
1. Constructor method
/**
* Person class: defines a person, has an attribute name, and a getName method
* @param {String} name
*/
function Person(name) {
this.name = name;
this.getName = function() {
return this.name;
}
}
This style is a bit familiar to those of us who have written Java because constructing an object requires configuring some parameters, and the parameters must be assigned to this in the class. But the difference from Java is that JS uses functions to define classes, and parameters do not need to be defined types.
The class is written, let’s create a few objects:
var p1 = new Person("Jack");
var p2 = new Person("Tom");
console.log(p1 instanceof Person);//true
console. log(p2 instanceof Person);//true
The console output also proves that p1 and p2 are indeed object instances of class Person.
The advantage of this method is that different object instances can be constructed according to parameters. The disadvantage is that each instance object will generate a getName method version during construction, resulting in a waste of memory.
Of course, experienced programmers use an external function to replace the class method, so that each object shares the same method. The rewritten class is as follows:
//External function
function getName() {
return this.name;
}
function Person(name) {
this.name = name;
this.getName = getName;// Pay attention here
}
Haha, some people may think that the code style is a bit unsatisfactory. It is not as compact as Java. But it can indeed reduce memory consumption.