loading...
Cover image for Duck Punching
Thinkster

Duck Punching

josepheames profile image Joe Eames ・2 min read

One of the very cool aspects of JavaScript, and other similar languages, is the dynamic nature of how you can treat the types in your application.

JavaScript is considered Dynamically Typed. This generally means that types are only checked at runtime. For example, if you try to do something on a number that can only be done on a string, this fails at runtime, but not at compile/design time. So you can write the code, but not run it.

So this:

image

Produces this error:

image

But ONLY at runtime. Trying this sort of thing in a statically typed language produces a design-time or compile-time error, such as the following in TypeScript, which shows up as soon as you type in the above code.

image

So this capability leads to the next cool aspect of JavaScript. Duck Typing.

The basic principle is that if it walks like a duck and quacks like a duck, it's a duck. So given the following two JavaScript classes:

image

We can feed instances of either class to the following function:

image

And have no problems. They both walk like a duck and quack like a duck, so they can both be treated as ducks.

And finally, we arrive at our subject: Monkey Patching (This is sometimes called Duck Punching). This is the ability to modify an object at runtime to give it the "shape" or "interface" that we want it to have, or add new capabilities it didn't have in the first place.

In JavaScript, we can add properties and methods to an object at runtime like so:

image

So even though the duck variable is now an instance of duck, we have modified it and given it a new function, the laserCannon function.

Note, you can do this on objects you don't own (3rd party objects). This is almost universally considered a bad idea. For example:

image

Now our document looks like a duck. But there are all kinds of problems with doing something like this, so unless you REALLY know what you're doing, don't ever do this. In fact, this very tactic led to a new enhancement of the JavaScript language getting changed. Some hilarity ensued, and the incident was nicknamed SmooshGate.

While dangerous, it does show the flexibility and power of JavaScript. But as your friendly neighborhood Spiderman says, "with great power, comes great responsibility."

Happy coding!

Signup for my newsletter here.

Visit Us: thinkster.io | Facebook: @gothinkster | Twitter: @gothinkster

Posted on by:

josepheames profile

Joe Eames

@josepheames

Mormon, Christian, Father, Educator, CEO of Thinkster.io, Organizer of @ngconf, @frameworksummit & React Conf. Front end developer, and Software Craftsmanship Evangelist.

Thinkster

The best place on the web for tutorials and screencasts covering Angular, AngularJS, React, Ionic, Swift, MEAN, and more!

Discussion

markdown guide