Skip to content
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

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Source/Core/Core.js
Original file line number Diff line number Diff line change
Expand Up @@ -368,6 +368,7 @@ var cloneOf = function(item){
};

Array.implement('clone', function(){
if(this.slice) return this.slice(0);
Copy link
Member

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/

var i = this.length, clone = new Array(i);
while (i--) clone[i] = cloneOf(this[i]);
return clone;
Expand Down Expand Up @@ -397,6 +398,7 @@ Object.extend({
},

clone: function(object){
if(Object.create) return Object.create(object);
Copy link

@AmraniCh AmraniCh Oct 16, 2020

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/

Copy link
Member

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/

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.

var clone = {};
for (var key in object) clone[key] = cloneOf(object[key]);
return clone;
Expand Down