Search code examples
javascriptmethodsprototypal-inheritance

JS: why do i need brackets to call a method on number?


function func2method(f){
    return function(y) {
        return f(this, y);
    };
}

Number.prototype.add = func2method(function(x, y){return x+y});

Why do I have to use brackets to call this method on a number?

For example, 3.add(4) won't work while (3).add(4) works perfectly fine.


Solution

  • Because 3.0 is not the same as (3)['0']

    Literals are interpreted differently. The point . represents a decimal point on a numeric literal, but the point . on an object represents a property accessor (translated to square bracket notation above)