2

私は方法について深刻な問題を抱えています。だからこれは私の方法です:

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

そしてブラウザは私に与えています:

Uncaught RangeError:最大呼び出しスタックサイズを超えました

行で:

for (i in this) {

誰かが同じ問題を抱えている可能性はありますか?

4

1 に答える 1

1

I can make javascript objects that can break your clonage function if that is an achievement of any kind :).

check: http://jsfiddle.net/Bd6XL/2/

var x = { 
    a: 5, 
    b: "asdf" 
};
var y = { 
    a: 5, 
    b: "asdf" 
};

x.y = y;
y.x = x;

Clone any of them. Yes it wont work because of circular references. Try to debug your object and see if there is any circular reference.

Also try limit your clone to what you really need.

EDIT:

Check out this question about cloning: What is the most efficient way to deep clone an object in JavaScript?

There are quite a few answers. Try the accepted one if you use jQuery:

// Shallow copy
var newObject = jQuery.extend({}, oldObject);

// Deep copy
var newObject = jQuery.extend(true, {}, oldObject);
于 2012-09-07T13:41:56.010 に答える