3
\$\begingroup\$

Are there any pitfalls in changing the prototype of the String object? I'd like to change the word substr to "left":

String.prototype.left = function(n) {
 return this.substr(0,n)
}

Is this ok, or should I just get over it?

Next, I'm going to write a .right(), a .mid(), a .val() and a .int().

Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Oct 24, 2014 at 18:39
\$\endgroup\$
2
  • \$\begingroup\$ I wouldn't do it, extending builtin objects is an anti-pattern IMO. \$\endgroup\$ Commented Oct 24, 2014 at 19:13
  • \$\begingroup\$ @elclanrs that could be a fine answer if you also propose an alternative with sample code \$\endgroup\$ Commented Oct 24, 2014 at 19:24

1 Answer 1

6
\$\begingroup\$

Extending native objects is bad practice.

  • When you're expecting nothing, then something shows up. That's natural behavior of prototypes.

  • Forwards compatibility. The same reason why Object.keys(someObjectInstance) is designed that way instead of someObjectInstance.keys() - because some implementations may already have used keys as a property. So what if ECMAScript 9 wants to use left() and right() for some string operation, your app will break.

For alternatives:

  • You can create your own functions in a separate namespace, that looks like the native functions. For instance, the native forEach looks like array.forEach(fn). Underscore writes it differently with _.forEach(array,fn).

  • You can extend native objects. Mileage may vary on this one as some (not sure which, but most) native objects are not subclassable.

  • You could create "wrapper objects" that just wrap the object into another object, who has methods that operate on the wrapped object. A good example is jQuery which wraps an array of stuff in a "jQuery object" which hosts a myriad of DOM manipulation methods that operate on that set.

  • Create a custom object that doesn't necessarily extend/inherit/wrap anything. Something like var string = new CustomString('hello world').

answered Oct 24, 2014 at 20:02
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.