Manngo
Manngo

Reputation: 16291

JavaScript: why are some functions not methods?

I was once asked by a student why we write:

that is, why one has the variable as a parameter, while the other is applied to the variable.

I explained that while toLowerCase is a method of string objects, parseInt wasn’t designed that way. OK, so it’s window.parseInt, but that just makes it a method of a different object.

But it struck me as an inconsistency — why are some string or other functions not methods of their corresponding objects?

The question is why? Is there a technical reason why parseInt and other functions are not methods, or is that just a historical quirk?

Upvotes: 4

Views: 142

Answers (3)

user2694295
user2694295

Reputation: 390

The development progress of the JavaScript language is quite fast in recent years. With that in mind, a lot of things are still in the API due to backward compatibility - historical reasons as you said. Although I can't say that's the only reason.

In JavaScript, you can approach a problem not just with Object oriented paradigm (where methods of objects usually shares a common state). Another, functional approach can be applied quite easily without getting into too much trouble with JavaScript language.

JavaScript gives great power to its users with many possibilities of approaching a problem. There is a saying: "With Great Power Comes Great Responsibility".

Upvotes: 0

kwah
kwah

Reputation: 1149

In this specific case it makes sense with respect to encapsulation.

Consider parseInt() - it is taking a value of an unknown type from an unknown location and extracting an integer value from it. Which object are you going to have it a method of? All of them?

String.toUpperCase() should only take a string as input (else something which may be cast as a string) and will return a string. This is well encapsulated within a small subset of cases, and since values are not strongly typed it seems logical to not have it as a global function.

As for the rest of JavaScript I have no idea nor do I have insight into the real reason it was done this way, but for these specific examples it appears to me to be a reasonable design decision.

Upvotes: 2

deceze
deceze

Reputation: 522085

In general, Javascript was designed in a hurry, so questioning each individual design decision isn't always a productive use of your time.

Having said that, for parseInt in particular, the reason is simple to explain: it accepts pretty much any arbitrary type, like:

parseInt(undefined)  // NaN

Since you cannot implement undefined.parseInt(), the only way to do it is to implement it as a static function.

As of ECMAScript 2015, parseInt has been mirrored in Number.parseInt, where it arguably makes more sense than on window. For backwards compatibility window.parseInt continues to exist though.

Upvotes: 3

Related Questions