For more information about JS constructor overloading and factory methods, see.
Preface
Sometimes we want multiple methods for object initialization. For example, you can use an array composed of elements to initialize a Set object, instead of passing in the constructor parameter list to initialize it.
Heavy Load
By reloading this constructor method, let it execute different initialization methods based on different input parameters.
The Code is as follows:
Function Set (){
This. values ={}; // use the property of this object to save this set.
This. n = 0; // number of values in the Set
// If an object of the class array is input, add this element to the set.
// Otherwise, add all parameters to the set
If (arguments. length ===1 & isArrayLike (arguments [0]) {
This. add. apply (this, arguments [0]); // add the object to the set using apply ().
} Else if (arguments. length> 0 ){
This. add. apply (this, arguments); // use the add () method to add all parameters to the set.
}
}
The Set () constructor defined in this Code can explicitly pass in a group of elements as a parameter list, or an array composed of elements. However, this constructor has multiple meanings. If a parameter of a set is an array, this constructor cannot be used to create this set. (to do this, you must first create an empty set, then, the add () method is called ).
Factory method
The method of a class is used to return an instance of the class.
The Code is as follows:
// The Factory method initializes the Set object through Arrays
Set. fromArray = function (arr ){
Var s = new Set ();
S. add. apply (s, arr );
Return s;
};
Factory methods with different names are used to perform different initialization. However, since constructors are public identifiers of classes, each class can have only one constructor. However, this is not a mandatory rule.
Auxiliary Constructor
Call Set () as a function to initialize this new object.
The Code is as follows:
// Define an auxiliary constructor of the Set Type
Function SetFromArray (arr ){
// Call Set () as a function to initialize this new object
// Input the arr element as a parameter
Set. apply (this, arr );
}
// Configure the prototype so that SetFromArray can create a Set instance
SetFromArray. prototype = Set. prototype;
JavaScript cannot be done.