0

I'm using the code below and It's working good, but when I try to use JQuery at the same time, then I'm getting the below error, I was reading some posts and I think the problem is that no is possible extend the Object.prototype without checking hasOwnProperty(), but I don't know how to solve that, can someone give me a hand?

Code:

Object.prototype.clone = function () {
    var i, newObj = (this instanceof Array) ? [] : {};
    for (i in this) {
        if (i === 'clone') {
            continue;
        }
        if (this[i] && typeof this[i] === "object") {
            newObj[i] = this[i].clone();
        } else {
            newObj[i] = this[i];
        }
    }
    return newObj;
    };

Error:

Uncaught TypeError: Object function () {
    var i, newObj = (this instanceof Array) ? [] : {};
    for (i in this) {
        if (i === 'clone') {
            continue;
        }
        if (this[i] && typeof this[i] === "object") {
            newObj[i] = this[i].clone();
        } else {
            newObj[i] = this[i];
        }
    }
    return newObj;
} has no method 'exec' 
darkcode
  • 868
  • 12
  • 27
  • On jsFiddle you got error also? – Dvir Oct 06 '13 at 18:01
  • 2
    I'd suggest not putting the method on `Object.prototype`. Instead put it as a method on `Object` so that it's not inherited, and pass the object to be cloned as the first argument. `Object.clone(foo)` – user2736012 Oct 06 '13 at 18:01
  • 1
    @Dvir: What does jsFiddle have to do with anything? – user2736012 Oct 06 '13 at 18:02
  • Try not to modify built in prototypes especially Object and Array. Here object is the base for almost everything so what you have extended will be available for Array as well, But you can try using ecma5 object define property and make enumerable to false for this property. Try this fiddle http://jsfiddle.net/ywyXS/ – PSL Oct 06 '13 at 18:05
  • Thanks PSL that fixed the error! – darkcode Oct 06 '13 at 18:18
  • viktorpr7: Be careful. There are other considerations to take into account. @PSL's suggestion to set `enumerable:false` doesn't solve all problems related to extending `Object.prototype`. And browser support is another consideration. – user2736012 Oct 06 '13 at 18:19
  • @user2736012 Yes, it is ecma5, not supported across... But always better not to extent built in prots, you never know what you are going to break. – PSL Oct 06 '13 at 18:22
  • exact duplicate of [How to define method in javascript on Array.prototype and Object.prototype so that it doesn't appear in for in loop](http://stackoverflow.com/questions/13296340/how-to-define-method-in-javascript-on-array-prototype-and-object-prototype-so-th) – Bergi Oct 06 '13 at 18:30

1 Answers1

0

Add the following function to your clone object:

Object.prototype.clone.exec=function() {
    //your codes
};
Roman Vottner
  • 12,213
  • 5
  • 46
  • 63
Danyu
  • 509
  • 3
  • 7