0

I have written the following code snippet to enhance all the objects in JavaScript and would like to make this method available to all the JavaScript libraries that I write. How should I go about doing this in node.js?

Object.prototype.copy = function() {
    var that = this,
        obj = {};

    for (var key in that) {
        if (that.hasOwnProperty(key)) {
            obj[key] = that[key];
        }
    }

    return obj;
}
Ken Russell
  • 2,348
  • 5
  • 24
  • 39
  • 1
    In general it's not good practice to add methods to native objects in Javascript, since it can cause compatibility issues with other libraries. There's a good discussion of this topic [in this SO question](http://stackoverflow.com/questions/14034180/why-is-extending-native-objects-a-bad-practice). Furthermore, there are plenty of good libraries out there that have methods for cloning objects; [Lodash](http://lodash.com) comes to mind. – sgress454 Apr 03 '14 at 04:41
  • 1
    @ScottGress is 100% correct that this sort of thing is best avoided. He is also correct that there are libraries to provide the function, but I am not a fan of including an entire library just to get 10 lines of code. In answer to your question though, instead of assigning the function to `Object.copy` you would assign it to `Object.prototype.copy`. But again, you shouldn't. :-) – barry-johnson Apr 03 '14 at 05:11

1 Answers1

0

...removed: I was wrong...

Just as Scott Gress and barry-johnson pointed out in cimments, It's a very bad practice to change build-in types.

Leonid Beschastny
  • 50,364
  • 10
  • 118
  • 122