Take the advantages of the previous two:
a. Use constructors to define class attributes (fields)
b. Use prototypes to define class methods.
There is a third way. This method seems to be used by more people.
3. Comprehensive constructor/prototype
/* *
* Person class: defines a person, has an attribute name, and a getName method
* @param {String} name
*/
function Person(name) {
this.name = name;
}
Person.prototype.getName = function() {
return this.name;
}
In this way, people with different names can be constructed through the constructor, and the object instances also share the getName method, which will not cause memory waste.
But it seems that this coding style is still not as compact as Java classes. Properties, constructors (functions), and methods are all enclosed in curly brackets.
public class Person {
//Attribute (field )
String name;
//Constructor (function)
Person(String name) {
this.name = name;
}
//Method
String getName () {
return this.name;
}
}
In order to make the js code style more compact, move the method code hanging in the prototype to the braces of the function Person Inside.
function Person(name) {
this.name = name;
Person.prototype.getName = function() {
return this.name;
}
}
It seems amazing that it can be written like this ! Verify
var p1 = new Person("Jack") ;
var p2 = new Person("Tom");
console.log(p1.getName());//Jack
console.log(p2.getName());//Tom
No error is reported, and the console outputs correctly. The description can be written like this, haha.
Hmm, seems perfect.
a. Object instances can be constructed by passing parameters
b. Object instances all share the same method without causing memory waste
c. The code style is also relatively compact
But every time an object is new, it will Executing
Person.prototype.getName = function() {
return this.name;
}
causes unnecessary repeated operations. Because the getName method hangs on the prototype and only needs to be executed once. Just make a slight modification:
function Person(name) {
this.name = name;
if(Person._init==undefined) {
alert("I only execute it once!");
Person.prototype.getName = function() {
return this.name;
}
Person._init = 1;
}
}
new two objects,
var p1 = new Person("Andy");//new will pop up for the first time' I only do it once! '
var p2 = new Person("Lily");//The new object will no longer be executed in the future