shallow(浅い)コピーとdeep(深い)コピーのメモ。
jQueryのextendメソッドを使ったサンプル。
var oldObj = {
x: 0,
y: ['a', 'b', 'c']
};
// shallow copy
// プリミティブ型のプロパティは値をコピーする
// それ以外の型のプロパティは参照を渡す
var newObj1 = $.extend({}, oldObj);
// deep copy
// 全てのプロパティをコピー
var newObj2 = $.extend(true, {}, oldObj);
// コピー元のプロパティを変更
oldObj.x = 2;
oldObj.y[0] = 'd';
// shallow copy
console.log(newObj1.x); // 0
console.log(newObj1.y[0]); // d
// deep copy
console.log(newObj2.x); // 0
console.log(newObj2.y[0]); // a
No comments yet.
改行と段落タグは自動で挿入されます。
メールアドレスは表示されません。