Home > Web Front-end > JS Tutorial > body text

Basic knowledge about overloading and factory methods of JS constructors

WBOY
Release: 2016-05-16 17:38:15
Original
834 people have browsed it

is written in front

Sometimes we want to initialize objects in multiple ways. For example, initialize a Set object through an array of elements instead of initializing it by passing in the parameter list of the constructor

overload

By overloading this constructor method, it can execute different initialization methods according to the different parameters passed in.

Copy code The code is as follows:

function Set() {
this.values ​​= {}; // Use the properties of this object to save this collection
this.n = 0; // The number of values ​​in the collection

// If an array-like object is passed in, this element will be Add 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 collection using apply()
}else if(arguments.length > 0) {
this.add.apply(this, arguments); // Use the add() method to add all parameters to the collection
}
}

The Set() constructor defined in this code can explicitly pass in a set of elements as a parameter list, or it can pass in an array of elements. But this constructor is ambiguous. If a parameter of the collection is an array, the collection cannot be created through this constructor (in order to do this, you need to first create an empty collection and then explicitly call add() method).

Factory method

A class method is used to return an instance of the class.

Copy code The code is as follows:

// The factory method initializes the Set object through the array
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 initializations. But since the constructor is the public identifier of the class, each class can only have one constructor. But this is not a rule that must be followed.

Auxiliary constructor

Initialize this new object by calling Set() as a function

Copy code The code is as follows:

// Define an auxiliary constructor of the Set type
function SetFromArray(arr) {
// Initialize this new object by calling Set() as a function
// Pass the elements of arr as parameters
Set.apply(this, arr) ;
}
//Set the prototype so that SetFromArray can create Set instances
SetFromArray.prototype = Set.prototype;

Nothing is impossible with JavaScript, only unexpected

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template