すべてがオブジェクトであります
いくつかの浅いコピーを初めて目
浅度复制
var obj = {a:1,b:2,c:3}
var obj1 = {}
for(var prop in obj){
obj1[prop] = obj[prop]
}
obj["a"] = 100
console.log(obj)
console.log(obj1)
値をプリントアウトコピーは変更されませんので、OBJの変化の性質、完全な浅いコピー
次に、複製オブジェクトベルトの方法見 Object.assign()
var obj = {a:1,b:2,c:3}
var obj1 = Object.assign({},obj)
obj["a"] = 100
console.log(obj)
console.log(obj1)
あなたが言うならば
var obj = {a:1,b:2,c:{
a:1,b:2,c:{
a:1,b:2
},d:{
a:1,c:2,c:3
}
}}
私たちは深いコピーのために、以下のこの方法を使用することができるようにオブジェクトは、上記の方法は、仕事をしない、コピーを作ることです
var obj1 = cloneObject (obj,{})
function cloneObject(source,target){
for(var prop in source){
if(typeof(source[prop]) === "object" && source[prop] !== null){
var obj = {}
cloneObject(source[prop],obj)
target[prop] = obj
}else{
target[prop] = source[prop]
}
}
return target
}
console.log(obj1)
このように、私がobjの値を変更すると、OBJ1が変更されない、完全な深いコピー
もちろん、これはより深いコピーへの道よりも
次のより多くの困難を見て
我々は必要なときにDOM要素をコピーし、あなたも(あなたが知っていれば、プロトタイプオブジェクトの記述がよりよく理解されるであろう)、これを選択することができます
<body>
<div class="div1"></div>
<div class="div1"></div>
<div class="div1"></div>
<script>
var obj1={};
Object.defineProperties(obj1,{
a:{
value:1
},
b:{
writable:true,
enumerable:true,
value:2
},
c:{
configurable:true,
writable:true,
value:3
},
d:{
enumerable:true,
set:function(value){
this._d=value;
},
get:function(){
if(!this._d) this._d=0;
return this._d;
}
}
});
var obj={
a:1,
b:[1,2,3],
c:{
a:"a",
b:true,
c:{
a:new Date(),
b:/^[a-z](!=[0-9])$/i,
c:{
a:new XMLHttpRequest(),
b:[
[1,2,3,4,5],
[2,3,4,5,6],
[3,4,5,6,7]
],
c:{
a:[
{a:1,b:2},
{a:2,b:3},
{a:3,b:4}
],
b:function(){
console.log("aaa");
},
c:obj1,
d:document.querySelector(".div1")
}
}
}
}
}
var obj2=cloneObject({},obj);
var names = Object.getOwnPropertyNames(source)
for(var i =0;i<names.length;i++){
var desc = Object.getOwnPropertyDescriptor(source,names[i])
if(typeof desc.value ==="object" && desc.value!==0){
var objs
if(desc.value.constructor === Date){
objs = new desc.value.constructor(desc.value)
}else if(desc.value.constructor === RegExp){
objs = new desc.value.constructor(desc.value.source,desc.value.flags)
}else if(desc.value.__proto__.__proto__&&desc.value.__proto__.__proto__.constructor === HTMLElement){
objs = document.createElement(desc.value.nodeName)
}else{
objs = new desc.value.constructor()
}
Object.defineProperty(source,names[i],{
writable: desc.writable,
enumerable: desc.enumerable,
configurable: desc.configurable,
value: objs
})
cloneObject(objs,desc.value)
}else{
Object.defineProperty(source,names[i],desc)
}
}
return target
}
</script>
</body>
フロントエンドのために
私はこれまで堪能からだった
唯一の道でした