1

I have seen some people regard extending the natives prototypes in Javascript with disdain. I was thinking about doing it, because of syntactic convenience. I.e.

function(array, element)

can be more cumbersome to write and less readable than

array.function(element)

But the second can only be acheived (AFAIK) by extending the Array prototype. Is there something wrong with extending native prototypes, and will doing this somehow haunt be me later?

3

1 Answer 1

1

It can conflict with other libraries trying to do the same.

It can conflict with future methods added to native objects.

If anyone is using for (var i in array) without proper hasOwnProperty() checks, their code may/probably will break because the new method may show up in the iteration in older browsers.

Sign up to request clarification or add additional context in comments.

8 Comments

You mean without proper hasOwnProperty checks?
But you can always check to see if it already exists to prevent clashes and make it future-proof. E.g. if I wanted to add foo to the Array prototype, I would first check if(Array.foo).
@Peter Of The Corn - you can only check if it already exists and defer to a built-in method if you KNOW that your method has the EXACT same implementation as the new built-in one. That can be safe for methods that are already introduced in newer browsers, but isn't feasible for ones that don't exist yet because you may be deferring to a built-in method that works differently than what you coded and tested your app with.
The problem of overwriting methods is somewhat alleviated with the latest ECMA spec. So library assigns Array.foo and when done correctly for(var i in Array) will not show the property foo and Array.foo=bar produces an error. I know that not all browsers support this now, but given some time this particular argument may carry less weight.
@qw3n - It will be a very long time before all browsers you might want to support have that ECMA feature. Because of that, you'd have to make sure nobody was unsafely iterating over an array. We're talking about the risks here. I'm not saying you can't do it, just discussing what the risks are.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.