Produces this error:
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.
We can feed instances of either class to the following function:
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.
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:
Signup for my newsletter here.
Posted on by: