-
Notifications
You must be signed in to change notification settings - Fork 512
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Use native clone methods when available #2719
base: master
Are you sure you want to change the base?
Conversation
Just a little of feature detection to leverage the power of native clone!
@@ -368,6 +368,7 @@ var cloneOf = function(item){ | |||
}; | |||
|
|||
Array.implement('clone', function(){ | |||
if(this.slice) return this.slice(0); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Array.clone
clones also eventual objects inside the array. Doing a early return here using return this.slice(0);
would keep the objects reference and add a new behaviour. http://jsfiddle.net/syv2he8o/
@@ -397,6 +398,7 @@ Object.extend({ | |||
}, | |||
|
|||
clone: function(object){ | |||
if(Object.create) return Object.create(object); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The Object.create
function creates a new object that inherits directly from the one passed as the first argument, in opposite the Object.clone
creates a new object with always the base Object
prototype, this is actually changing the Object.clone
behavior. https://jsfiddle.net/AmraniCh/u86c0qoL/
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@AmraniCh: In your fiddle, you should use Array.clone
with arrays and not Object.clone
https://jsfiddle.net/vu5xt0ed/
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@SergioCrisostomo Actually it Object.clone
, I'm just making a test with the array type.
The Mootools Object.clone
always clone an object and return a new one with the Object
prototype, if we add the return Object.create(object)
then the Object.clone
will use the object passed as an argument (can be an array, function ..) as a prototype of the newly created object, which is not the native behavior of the Object.clone
.
Just a little of feature detection to leverage the power of native clone!