Take advantage of the previous two:
A, use constructors to define class properties (fields)
B, the method of defining the class in a prototype way.
There is a third way. This way seems to use more people.
3. Synthetic constructor/prototype
Copy Code code as follows:
/**
* Person class: Defines a human, has a property 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 name can be constructed by constructors, and object instances share GetName methods without causing memory waste.
But it seems that the code style is still not as compact as Java classes, attributes, construction methods (functions), methods are wrapped in curly braces.
Copy Code code as follows:
public class Person {
Properties (Fields)
String name;
Constructor Method (function)
Person (String name) {
THIS.name = name;
}
Method
String GetName () {
return this.name;
}
}
To make the JS code more compact, move the method code that hangs in the prototype to the curly braces of the function person.
Copy Code code as follows:
function person (name) {
THIS.name = name;
Person.prototype.getName = function () {
return this.name;
}
}
It seems very magical, but also can write Ah! Verify
Copy Code code as follows:
var p1 = new Person ("Jack");
var p2 = new Person ("Tom");
Console.log (P1.getname ());//jack
Console.log (P2.getname ());//tom
No error, the console also correctly output. Description can be so written, hehe.
Well, it seems to be perfect.
A, you can construct an object instance by passing parameters
B, object instances share the same method does not cause memory waste
C, the code is also more compact style
But every time a new object is executed
Person.prototype.getName = function () {
return this.name;
}
resulting in unnecessary duplication of operations. Because the GetName method hangs on the prototype, it can only be done once. Just a little bit of makeover:
Copy Code code as follows:
function person (name) {
THIS.name = name;
if (person._init==undefined) {
Alert ("I only do it once!") ");
Person.prototype.getName = function () {
return this.name;
}
Person._init = 1;
}
}
New Two objects,
Copy Code code as follows:
var p1 = new Person ("Andy");//The first time new will pop up ' I only do it once! '
var p2 = new Person ("Lily")//new object will not be executed again