Skip to main content

Javascript: The prototype pattern

The prototype pattern is composed of two parts, the constructor function, and the prototype.

The constructor function has the responsibility of holding the data while the prototype will the define the functions.

The advantage of this approach is that all state variables held in the constructor part will be unique to the instance, while all methods defined in the prototype will be shared across all instances.

Implementing the constructor part: of the pattern consists in adding any arguments to the function definition and setting in variable using the 'this' keyword.

Implementing the prototype part: consists of setting the constructor's prototype to a new literal object containing a property for each function.

Finally, it should be noted that by convention, the constructor function should be cased in Pascal case. Typically anytime a function is cased as such in Javascript hints it is a constructor function and should be used with the new keyword.

Comments

Popular posts from this blog

Rxjs Forkjoin vs Zip

These Rxjs combination operators are handy to make Rest calls in parallel and combine their results. Both take n observables and will return the results, with the difference that forkJoin will complete even if one of the nested observables errors of completes.

React JS Patterns

React JS is always evolving, and evolving quickly. These evolutions can be very significant ones, for example, the addition of hooks. React has a lot of code patterns, often these patterns are motivated by the DRY and/or the open-close principle. These patterns sometimes come in to replace a previous one, yet the previous ones still stays in use, as a consequence, the list of patterns keep growing. The goal of the next few posts will be to list the patterns commonly used in React JS developpement. Some patterns are more specific to JSX and I will start with these, and maybe add patterns specific to Redux.

Object.create vs. Object.Assign

The two functions return a new Object but with a difference. Object.assign will go through an enumerable and copy it's properties. Object.create will create a new empty object but link it's proto chain to the old object. One way to view this is with JSON.stringify(newCreatedObject) this would return an empty object, since all the properties are not part of the object's own properties, but inherited through prototype inheritance. In both case, the advantage is it allows to extended existing objects without modifying the original. This is particularly important when receiving arguments from a caller, in this case it's better to use these methods instead of modifying the caller's object since he might have planned to use it again later, expecting it to be in it's original state.