I try to extend JavaScript Math
. But one thing surprised me.
When I tried to extend it by prototype
Math.prototype.randomBetwee
That's because there's Math
is an object, not a function
.
In javascript, a function
is the rough equivalent of a class in object oriented languages. prototype
is a special property which lets you add instance methods to this class1. When you want to extend that class, you use prototype
and it "just works".
Now let's think about what Math
is. You never create a math object, you just use it's methods. In fact, it doesn't make sense to create two different Math
objects, because Math
always works the same! In other words, the Math
object in javascript is just a convenient way to group a bunch of pre-written math related functions together. It's like a dictionary of common math.
Want to add something to that group? Just add a property to the collection! Here's two easy ways to do it.
Math.randomBetween = function() { ... }
Math["randomBetween"] = function() {... }
Using the second way makes it a bit more obvious that it's a dictionary type collection, but they both do the same thing.