Why is parseInt a function instead of a method?
Function:
var i = parseInt(X);
Method:
var i = X.parseInt();
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);
// ...
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With