To do clone for any object in JavaScript will not be simple or straightforward. You will run into the problem of erroneously picking up attributes from the object’s prototype that should be left in the prototype and not copied to the new instance. If, for instance, you are adding a clone method to Object.prototype, as someone depict, you will need to explicitly skip that attribute. But what if there are other additional methods added to Object.prototype, or other intermediate prototypes, that you don’t know about? In that case, you will copy attributes you shouldn’t, so you need to detect unforeseen, non-local attributes with the hasOwnProperty method.
the very simple way
1 | var cloneObj = JSON.parse(JSON.stringify(obj)); |
In this way, it will discard constructor.
think deep
1 | Object.prototype.clone = function () { |
some interior object clone
1 | /* Method of Array */ |
some test
1 | [1]==[1] |