// code from jb51.net
function Person(name) {
this.Name = name;
}
Person.prototype.SayHello = function() {
alert('Hello, ' this.Name);
}
Person. prototype.SayBye = function() {
alert('Goodbye, ' this.Name);
}
However, sometimes, for the convenience of writing and maintenance, we will Write the declaration of the public method into an object and assign it to Person.prototype, for example:
// code from jb51.net
function Person(name) {
this.Name = name;
}
Person.prototype = {
SayHello: function() {
alert('Hello, ' this.Name);
},
SayBye: function() {
alert('Goodbye, ' this.Name);
}
}
Using this method, when this class has a large number of public methods, there is no need to maintain many Person identifiers. If the name of this class needs to be changed one day, then There are only two changes, one is the declaration of function, and the other is the identifier in front of prototype. If the former method is used, then as many public methods as there are, N 1 identifiers need to be maintained, although it can be used Find and replace, but in terms of stability, find and replace may cause some errors, which increases the cost of maintenance.
Although this method adds convenience to our maintenance, it also causes another hidden problem, which is the problem of losing the constructor attribute of the class.
// code from jb51.net
function Person1 (name) {
this.Name = name;
}
Person1.prototype.SayHello = function() {
alert('Hello, ' this.Name);
}
Person1.prototype.SayBye = function() {
alert('Goodbye, ' this.Name);
}
// code from jb51.net
function Person2(name) {
this.Name = name;
}
Person2.prototype = {
SayHello: function() {
alert('Hello, ' this.Name);
},
SayBye: function() {
alert('Goodbye, ' this.Name);
}
}
alert(new Person1('Bill').constructor);
alert(new Person2('Steve').constructor);
Running the above test code we can find that the constructor attribute of Person1 is the constructor of the Person1 class, but the constructor attribute of Person2 is Object, then in Problems arise when you need to use the constructor attribute to determine the object type.
Therefore, when writing a JavaScript class, if you do not need to use the constructor attribute to obtain the type of the object, then I personally prefer to use the second writing method, but if you need to use the constructor attribute to implement your own reflection mechanism or GetType function Wait, then we must use the first way of writing.
Of course, if you do not rely on the constructor attribute when implementing your own reflection mechanism or GetType function, then both writing methods are acceptable, such as maintaining an additional member variable to identify your own type, etc. You can also use some ready-made JS frameworks. Some frameworks have already implemented the implementation of classes in JS, such as js.class. It depends on your personal needs.