JavaScript cloning a "class" instance
This question already has an answer here:
$.extend
is only cloning plain objects. If the object has a constructor then it is not cloned, but just copied.
From the $.extend
source:
if ( jQuery.isPlainObject(copy) /* ... */) {
// do the recursive $.extend call and clone the object
} else if ( copy !== undefined ) {
target[ name ] = copy;
// ^^^^^ just copy
}
So $.extend()
will call isPlainObject(el)
which will return false, because el
has an constructor and instead of cloning the el
is copied. So states[1].elements[0]
is the same object as states[0].elements[0]
because it was not cloned.
If we modify your example from:
function Element(){
this.changes = {};
}
var el = new Element(); // $.isPlainObject(el); <- false
// ...
into:
var el = { changes: {} }; // $.isPlainObject(el); <- true
// ...
It will clone the el
properly. See it HERE .
您可以使用http://documentcloud.github.com/underscore/#clone克隆对象,如:
var cloned = _.clone(states[0]);
链接地址: http://www.djcxy.com/p/24766.html
下一篇: JavaScript克隆一个“类”实例