To create objects in JS, there are various patterns that can be followed.
These patterns are:
- Factory pattern
- Constructor pattern
- Prototype pattern
- Dynamic prototype pattern
With the factory pattern, we create a factory that creates specified objects and returns their reference. Every time we call the factory we get a new instance.
Consider this example, where we want to create objects for a computer that will contain their memory capacities (ram and hard disk).
To create a factory, we write this code:
Now we create an object by calling the factory, like this:
With the constructor pattern we don’t return the instance from the function — instead, we use the new operator along with the function name.
The constructor for the last example will be created like this:
Note: we’re not returning the object from the computer constructor.
You can read more about prototypes in the MDN Web Docs.
In a prototype pattern, we create a blank object and assign properties (and functions) to its prototype, with some default values. Then we create a blank object and assign the actual values for the properties.
This pattern can be represented like this:
Now consider if we create a new object of the computer with default values.
var computer1 = new computer();
//Created object with default valuesconsole.log('ram' in computer1); //returns true
console.log(computer1.hasOwnProperty('ram')); //returns false
This is because the
in operator searches for the property first in the object's root and then the search continues in the prototype of the object whereas
hasOwnProperty restricts its search to the root elements of the object in which the property is being searched.
Dynamic Prototype Pattern
The dynamic prototype pattern is a hybrid of the constructor pattern and the prototype pattern.
In this pattern properties are referenced with this operator. We create the member functions in the prototype space of the object, if the member function does not exist: