Breaking the MagiJSian’s Code: JavaScript Object Creation Patterns, Revealed!

Basic Sleight of Hand: `Object.create`

The trick to trump all tricks: Create a brand new object; link it to another object. Behaviour delegation is what JavaScript ‘inheritance’ is really all about.
When the property cannot be found on the object in question, it delegates to the next object up the prototype chain.

Creating a ‘totally blank’ object

ES6 Classes

Of course, to be a modern magician, you’ve got to have class. Since ECMAScript 2015, we’ve had access to a new kind of syntax for constructing objects: the class keyword. We also were given the extends keyword, for emulating traditional class inheritance and creating a superclass/subclass relationship.

Pseudo-Classical

Harry Houdini is trying to prepare his next illusion. He’s getting tired of repeating the same props, but he also doesn’t want to make everything from scratch.

Note: use of the `constructor` property to check type is not optimal: I recommend this https://css-tricks.com/understanding-javascript-constructors/ for further discussion on the topic.
function Constructor() { 
// Add properties you want to be unique to an object
}
Constructor.prototype.propertyName = // a shared property;Constructor.prototype.methodName = function() { // a shared method }
function Constructor() { 
// Add properties you want to be unique to an object
if(!this.propertyName) {
Constructor.prototype.propertyName = // shared property;
}
if(typeof this.methodName !== 'function') {
Constructor.prototype.methodName = function() { // shared method }
}
// We checked if the properties/methods existed on 'this', (or a prototype in 'this's prototype chain).
}
For more depth, and discussion of the Object.defineProperty method from earlier: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties

Objects Linked to Other Objects (OLOO)

Phew! Old Houdini had to put up with a lot of complexity. A modern mage realised this and came up with a new trick harnessing the power of Object.create in a different way.

The splitting up of the stages of object instantiation allows for some neat ‘inheritance’ type tricks
The magician’s ultimate secret revealed

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Nick Stebbs

Nick Stebbs

1 Follower

Ruby/JavaScript developer on the path of mastery, thanks to LaunchSchool.