Extending Math object through prototype doesn't work

前端 未结 4 1251
长发绾君心
长发绾君心 2021-02-05 06:21

I try to extend JavaScript Math. But one thing surprised me.

When I tried to extend it by prototype

Math.prototype.randomBetwee         


        
4条回答
  •  甜味超标
    2021-02-05 06:52

    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.

提交回复
热议问题