Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't parseInt a method?

Tags:

javascript

Why is parseInt a function instead of a method?

Function:

var i = parseInt(X);

Method:

var i = X.parseInt();
like image 965
Phillip Senn Avatar asked Feb 21 '12 14:02

Phillip Senn


1 Answers

Edit:

I'm not 100% sure why parseInt isn't a method of String, except that it can be run on anything. Seems it could be part of Math but it isn't really a mathematical operation either.

End Edit

parseInt is a method of the global object. In the browser, the global object is window. You could call window.parseInt(), but the JS engine lets you shortcut calls to global methods.

That said, there is some cost to it as the engine must scan the scope chain looking for definitions of parseInt. Generally, if I am making a single to call to such a method within a scope, I will reference it off the global:

var foo = function (someString) {
    var bar;

    // ...

    bar = window.parseInt(someString, 10);

    // ...
};

If my code needs to make more than one call to the method within a scope, however, I localize it and use the reference:

var foo = function (someString, someOtherString) {
    var parseInt = window.parseInt,
      bar,
      baz;

    // ...

    bar = parseInt(someString, 10);
    baz = parseInt(someOtherString, 10);

    // ...
};
like image 170
JAAulde Avatar answered Oct 19 '22 01:10

JAAulde