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()
.
-
\$\begingroup\$ I wouldn't do it, extending builtin objects is an anti-pattern IMO. \$\endgroup\$elclanrs– elclanrs2014年10月24日 19:13:50 +00:00Commented Oct 24, 2014 at 19:13
-
\$\begingroup\$ @elclanrs that could be a fine answer if you also propose an alternative with sample code \$\endgroup\$janos– janos2014年10月24日 19:24:14 +00:00Commented Oct 24, 2014 at 19:24
1 Answer 1
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 ofsomeObjectInstance.keys()
- because some implementations may already have usedkeys
as a property. So what if ECMAScript 9 wants to useleft()
andright()
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 likearray.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')
.