Apa adalah cara yang paling efisien untuk clone objek JavaScript? I've terlihat obj = eval(uneval(o));
sedang digunakan, tetapi itu's non-standar dan hanya didukung oleh Firefox.
I've dilakukan hal-hal seperti obj = JSON.mengurai(JSON.stringify(o));
tapi pertanyaan efisiensi.
I've juga terlihat rekursif fungsi menyalin dengan berbagai kekurangan.
I'm terkejut tidak kanonik solusi yang ada.
It's disebut "terstruktur kloning", karya-karya eksperimental di Node 11 dan kemudian, dan mudah-mudahan akan mendarat di browser. Lihat ini answer untuk rincian lebih lanjut.
Jika anda tidak menggunakan Kencan, fungsi,
undefined,
Infinity`, RegExps, Peta, Set, Gumpalan, FileLists, ImageDatas, sparse Array, Diketik Array atau jenis kompleks lainnya dalam objek anda, salah satu yang sangat sederhana liner untuk deep clone objek adalah:
JSON.mengurai(JSON.stringify(objek))
const a = {
string: 'string',
number: 123,
bool: false,
nul: null,
date: new Date(), // stringified
undef: undefined, // lost
inf: Infinity, // forced to 'null'
re: /.*/, // lost
}
console.log(a);
console.log(typeof a.date); // Date object
const clone = JSON.parse(JSON.stringify(a));
console.log(clone);
console.log(typeof clone.date); // result of .toISOString()
Lihat Corban's answer untuk tolok ukur.
Sejak kloning benda-benda yang tidak sepele (jenis kompleks, referensi melingkar, fungsi dll), yang paling utama perpustakaan menyediakan fungsi untuk mengkloning benda-benda. Don't reinvent the wheel - jika anda're sudah menggunakan perpustakaan, memeriksa jika memiliki sebuah objek kloning fungsi. Misalnya,
cloneDeep
; dapat diimpor secara terpisah melalui lodash.clonedeep modul dan mungkin adalah pilihan terbaik jika anda're sudah tidak menggunakan library yang menyediakan fungsi kloningsudut.copy
jQuery.memperpanjang(benar, { }, oldObject)
; .clone()
hanya klon elemen DOMUntuk kelengkapan, perhatikan bahwa ES6 menawarkan dua dangkal copy mekanisme: Object.assign()
dan menyebar operator.
Checkout penghitungan ini: http://jsben.ch/#/bWfk9
Dalam tes sebelumnya di mana kecepatan adalah perhatian utama saya menemukan
JSON.parse(JSON.stringify(obj))
untuk menjadi cara paling lambat untuk deep clone objek (lebih lambat dari jQuery.memperpanjang dengan deep
flag set benar oleh 10-20%).
jQuery.memperpanjang cukup cepat ketika mendalam
bendera diatur ke palsu
(dangkal clone). Ini adalah pilihan yang baik, karena itu termasuk beberapa tambahan logika untuk jenis validasi dan doesn't copy dari undefined sifat, dll., tapi ini juga akan memperlambat anda turun sedikit.
Jika anda mengetahui struktur dari benda-benda yang anda mencoba untuk mengkloning atau dapat menghindari mendalam bersarang array anda dapat menulis sederhana untuk (var i di obj)
loop untuk menduplikasi objek ketika memeriksa hasOwnProperty dan itu akan menjadi jauh lebih cepat dari jQuery.
Terakhir jika anda mencoba untuk mengkloning sebuah objek yang dikenal struktur dalam loop anda bisa mendapatkan LEBIH BANYAK lagi KINERJA dengan hanya di-lapisan clone prosedur dan manual membangun objek.
JavaScript jejak engine mengisap mengoptimalkan untuk..di
loop dan memeriksa hasOwnProperty akan memperlambat anda juga. Manual clone ketika kecepatan adalah mutlak harus.
var clonedObject = {
knownProp: obj.knownProp,
..
}
Berhati-hatilah menggunakan JSON.mengurai(JSON.stringify(obj))
metode Tanggal
benda - JSON.stringify(new Date())
mengembalikan sebuah string representasi tanggal dalam format ISO, yang JSON.parse()
doesn't mengkonversi kembali ke Tanggal
objek. Lihat jawaban ini untuk rincian lebih lanjut.
Selain itu, perlu dicatat bahwa, dalam Chrome 65 setidaknya, asli kloning adalah bukan cara untuk pergi. Menurut ini JSPerf, pertunjukan asli kloning dengan membuat fungsi baru hampir 800x lebih lambat daripada menggunakan JSON.stringify yang sangat cepat semua jalan di seluruh papan.
Jika anda menggunakan Javascript ES6 mencoba metode asli untuk kloning atau dangkal copy.
Object.assign({}, obj);
HTML standar termasuk internal terstruktur kloning/serialisasi algoritma yang dapat membuat dalam klon dari benda-benda. Hal ini masih terbatas untuk beberapa jenis built-in, tapi selain beberapa jenis yang didukung oleh JSON ini juga mendukung Tanggal, RegExps, Peta, Set, Gumpalan, FileLists, ImageDatas, sparse Array, Diketik Array, dan mungkin lebih banyak lagi di masa depan. Hal ini juga menjaga referensi dalam kloning data, yang memungkinkan untuk mendukung siklus dan rekursif struktur yang akan menyebabkan kesalahan untuk JSON.
The v8
modul di Node.js saat ini (sebagai Simpul 11) memperlihatkan terstruktur serialisasi API langsung, tetapi fungsi ini masih ditandai sebagai "eksperimental", dan tunduk pada perubahan atau penghapusan dalam versi masa depan. Jika anda'kembali menggunakan versi yang kompatibel, kloning sebuah objek sederhana seperti:
lang-js const v8 = require('v8'); const structuredClone = obj => { kembali v8.deserialize(v8.cerita bersambung(obj)); };
Browser saat ini tidak menyediakan antarmuka langsung untuk terstruktur kloning algoritma, tapi global structuredClone()
fungsi yang telah dibahas di whatwg/html#793 di GitHub. Seperti yang diusulkan saat ini, menggunakannya untuk sebagian besar tujuan akan menjadi seperti sederhana seperti:
lang-js const clone = structuredClone(asli);
Kecuali ini dikirim, browser' terstruktur clone implementasi yang hanya terkena tidak langsung.
Rendah-biaya overhead cara untuk membuat terstruktur clone dengan ada Api adalah untuk mengirim data melalui satu port MessageChannels. Port lainnya akan memancarkan sebuah pesan
acara dengan terstruktur clone terlampir .data
. Sayangnya, mendengarkan peristiwa ini tentu asinkron dan sinkron alternatif yang kurang praktis.
``lang-js
kelas StructuredCloner {
konstruktor() {
ini.pendingClones = Peta baru();
ini.nextKey = 0;
const channel = new MessageChannel(); ini.inPort = channel.port1; ini.outPort = channel.port2;
ini.outPort.onmessage = ({data: {key, value}}) => { const mengatasi = ini.pendingClones.mendapatkan(key); menyelesaikan(nilai); ini.pendingClones.menghapus(key); }; ini.outPort.start(); } cloneAsync(nilai) { kembali Janji baru(mengatasi => { const key = ini.nextKey++; ini.pendingClones.set(kunci, mengatasi); ini.inPort_.postMessage({key, value}); }); } } const structuredCloneAsync = window.structuredCloneAsync = StructuredCloner.prototipe.cloneAsync.bind(baru StructuredCloner); ``
``lang-js const utama = async () => { const asli = { date: new Date(), nomor: Matematika.random() }; asli.mandiri = asli; const clone = menunggu structuredCloneAsync(asli); // Mereka're objek yang berbeda: konsol.menegaskan(asli !== clone); konsol.menegaskan(yang asli.tanggal !== clone.tanggal); // Mereka're siklus: konsol.menegaskan(yang asli.mandiri === asli); konsol.menegaskan(clone.mandiri === clone); // Mereka mengandung nilai setara: konsol.menegaskan(yang asli.jumlah === clone.nomor); konsol.menegaskan(Nomor(asli.tanggal) === Jumlah(clone.tanggal));
konsol.log("Pernyataan lengkap."); }; main(); ``
Tidak ada pilihan yang baik untuk menciptakan terstruktur klon serentak. Berikut ini adalah beberapa praktis hacks sebaliknya.
sejarah.pushState()
dan sejarah.replaceState()
kedua membuat terstruktur clone pertama mereka argumen, dan menetapkan bahwa nilai sejarah.negara`. Anda dapat menggunakan ini untuk membuat terstruktur tiruan dari benda seperti ini:
lang-js const structuredClone = obj => { const oldState = sejarah.negara; sejarah.replaceState(obj, null); const clonedObj = sejarah.negara; sejarah.replaceState(oldState, null); kembali clonedObj; };
'use strict';
const main = () => {
const original = { date: new Date(), number: Math.random() };
original.self = original;
const clone = structuredClone(original);
// They're different objects:
console.assert(original !== clone);
console.assert(original.date !== clone.date);
// They're cyclical:
console.assert(original.self === original);
console.assert(clone.self === clone);
// They contain equivalent values:
console.assert(original.number === clone.number);
console.assert(Number(original.date) === Number(clone.date));
console.log("Assertions complete.");
};
const structuredClone = obj => {
const oldState = history.state;
history.replaceState(obj, null);
const clonedObj = history.state;
history.replaceState(oldState, null);
return clonedObj;
};
main();
Meskipun sinkron, hal ini dapat menjadi sangat lambat. Itu ditanggung semua biaya overhead yang terkait dengan memanipulasi sejarah browser. Memanggil metode ini berulang kali dapat menyebabkan Chrome untuk sementara menjadi tidak responsif.
The Pemberitahuan
konstruktor menciptakan terstruktur clone dari data yang terkait. Itu juga upaya untuk menampilkan browser pemberitahuan kepada pengguna, tapi ini diam-diam akan gagal kecuali anda meminta pemberitahuan izin. Dalam kasus anda memiliki izin untuk keperluan lain, kita'll segera menutup pemberitahuan kami've dibuat.
const structuredClone = obj => {
const n = new Notification('', {data: obj, silent: true});
n.onshow = n.close.bind(n);
return n.data;
};
'use strict';
const main = () => {
const original = { date: new Date(), number: Math.random() };
original.self = original;
const clone = structuredClone(original);
// They're different objects:
console.assert(original !== clone);
console.assert(original.date !== clone.date);
// They're cyclical:
console.assert(original.self === original);
console.assert(clone.self === clone);
// They contain equivalent values:
console.assert(original.number === clone.number);
console.assert(Number(original.date) === Number(clone.date));
console.log("Assertions complete.");
};
const structuredClone = obj => {
const n = new Notification('', {data: obj, silent: true});
n.close();
return n.data;
};
main();
Jika ada't builtin, anda bisa mencoba:
function clone(obj) {
if (obj === null || typeof (obj) !== 'object' || 'isActiveClone' in obj)
return obj;
if (obj instanceof Date)
var temp = new obj.constructor(); //or new Date(obj);
else
var temp = obj.constructor();
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
obj['isActiveClone'] = null;
temp[key] = clone(obj[key]);
delete obj['isActiveClone'];
}
}
return temp;
}
Sebuah Objek.menetapkan
metode adalah bagian dari ECMAScript 2015 (ES6) standar dan tidak persis apa yang anda butuhkan.
var clone = Object.assign({}, obj);
Objek.menetapkan() metode ini digunakan untuk menyalin nilai dari semua enumerable sendiri sifat-sifat dari satu atau lebih sumber objek ke objek target.
The polyfill untuk mendukung browser lama:
if (!Object.assign) {
Object.defineProperty(Object, 'assign', {
enumerable: false,
configurable: true,
writable: true,
value: function(target) {
'use strict';
if (target === undefined || target === null) {
throw new TypeError('Cannot convert first argument to object');
}
var to = Object(target);
for (var i = 1; i < arguments.length; i++) {
var nextSource = arguments[i];
if (nextSource === undefined || nextSource === null) {
continue;
}
nextSource = Object(nextSource);
var keysArray = Object.keys(nextSource);
for (var nextIndex = 0, len = keysArray.length; nextIndex < len; nextIndex++) {
var nextKey = keysArray[nextIndex];
var desc = Object.getOwnPropertyDescriptor(nextSource, nextKey);
if (desc !== undefined && desc.enumerable) {
to[nextKey] = nextSource[nextKey];
}
}
}
return to;
}
});
}
Kode:
// extends 'from' object with members from 'to'. If 'to' is null, a deep clone of 'from' is returned
function extend(from, to)
{
if (from == null || typeof from != "object") return from;
if (from.constructor != Object && from.constructor != Array) return from;
if (from.constructor == Date || from.constructor == RegExp || from.constructor == Function ||
from.constructor == String || from.constructor == Number || from.constructor == Boolean)
return new from.constructor(from);
to = to || new from.constructor();
for (var name in from)
{
to[name] = typeof to[name] == "undefined" ? extend(from[name], null) : to[name];
}
return to;
}
Tes:
var obj =
{
date: new Date(),
func: function(q) { return 1 + q; },
num: 123,
text: "asdasd",
array: [1, "asd"],
regex: new RegExp(/aaa/i),
subobj:
{
num: 234,
text: "asdsaD"
}
}
var clone = extend(obj);
Jauh di copy oleh kinerja: Peringkat dari terbaik sampai terburuk
Dalam salinan sebuah array dari string atau angka (satu tingkat - tidak ada referensi pointer):
Ketika sebuah array berisi angka-angka dan string - fungsi seperti .slice(), .concat(), .splice(), tugas operator "=", dan Garis bawah.js's clone fungsi; akan membuat deep copy dari array's elemen.
Di mana penugasan memiliki kinerja tercepat:
var arr1 = ['a', 'b', 'c'];
var arr2 = arr1;
arr1 = ['a', 'b', 'c'];
Dan .slice() memiliki kinerja yang lebih baik dari .concat(), http://jsperf.com/duplicate-array-slice-vs-concat/3
var arr1 = ['a', 'b', 'c']; // Becomes arr1 = ['a', 'b', 'c']
var arr2a = arr1.slice(0); // Becomes arr2a = ['a', 'b', 'c'] - deep copy
var arr2b = arr1.concat(); // Becomes arr2b = ['a', 'b', 'c'] - deep copy
Dalam salinan sebuah array dari objek (dua atau lebih tingkat - referensi pointer):
var arr1 = [{object:'a'}, {object:'b'}];
Menulis fungsi kustom (memiliki kinerja yang lebih cepat dari $.memperpanjang() atau JSON.mengurai):
function copy(o) {
var out, v, key;
out = Array.isArray(o) ? [] : {};
for (key in o) {
v = o[key];
out[key] = (typeof v === "object" && v !== null) ? copy(v) : v;
}
return out;
}
copy(arr1);
Menggunakan utilitas pihak ketiga fungsi:
$.extend(true, [], arr1); // Jquery Extend
JSON.parse(arr1);
_.cloneDeep(arr1); // Lo-dash
Di mana jQuery's $.memperpanjang memiliki kinerja yang lebih baik:
var clone = function() {
var newObj = (this instanceof Array) ? [] : {};
for (var i in this) {
if (this[i] && typeof this[i] == "object") {
newObj[i] = this[i].clone();
}
else
{
newObj[i] = this[i];
}
}
return newObj;
};
Object.defineProperty( Object.prototype, "clone", {value: clone, enumerable: false});
Ada perpustakaan (yang disebut "klon"), yang tidak cukup baik. Ini memberikan yang paling lengkap rekursif kloning/menyalin objek sewenang-wenang yang saya tahu. Ini juga mendukung referensi melingkar, yang tidak tercakup oleh jawaban yang lain, belum.
Anda dapat menemukannya pada npm](https://npmjs.org/package/clone), terlalu. Hal ini dapat digunakan untuk browser serta Node.js.
Berikut ini adalah contoh tentang bagaimana untuk menggunakannya:
Menginstalnya dengan
npm install clone
atau paket dengan Ender.
ender build clone [...]
Anda juga dapat men-download kode sumber secara manual.
Kemudian anda dapat menggunakannya dalam kode sumber anda.
var clone = require('clone');
var a = { foo: { bar: 'baz' } }; // inital value of a
var b = clone(a); // clone a -> b
a.foo.bar = 'foo'; // change a
console.log(a); // { foo: { bar: 'foo' } }
console.log(b); // { foo: { bar: 'baz' } }
(Disclaimer: saya penulis dari perpustakaan.)
Saya tahu ini adalah sebuah posting lama, tapi saya pikir ini mungkin dapat membantu untuk orang berikutnya yang tersandung bersama.
Selama anda don't menetapkan suatu objek untuk apa ia mempertahankan tidak ada referensi dalam memori. Jadi untuk membuat sebuah objek yang anda inginkan untuk berbagi di antara benda-benda lain, anda'll harus membuat pabrik seperti:
var a = function(){
return {
father:'zacharias'
};
},
b = a(),
c = a();
c.father = 'johndoe';
alert(b.father);
Kloning
Objek itu selalu menjadi perhatian di JS, tapi itu semua tentang sebelum ES6, saya daftar berbagai cara menyalin objek dalam JavaScript di bawah ini, bayangkan anda memiliki Objek di bawah ini dan ingin memiliki dalam salinan yang:
var obj = {a:1, b:2, c:3, d:4};
Ada beberapa cara untuk menyalin objek ini, tanpa mengubah asal:
function deepCopyObj(obj) {
if (null == obj || "object" != typeof obj) return obj;
if (obj instanceof Date) {
var copy = new Date();
copy.setTime(obj.getTime());
return copy;
}
if (obj instanceof Array) {
var copy = [];
for (var i = 0, len = obj.length; i < len; i++) {
copy[i] = cloneSO(obj[i]);
}
return copy;
}
if (obj instanceof Object) {
var copy = {};
for (var attr in obj) {
if (obj.hasOwnProperty(attr)) copy[attr] = cloneSO(obj[attr]);
}
return copy;
}
throw new Error("Unable to copy obj this object.");
}
var deepCopyObj = JSON.parse(JSON.stringify(obj));
var deepCopyObj = angular.copy(obj);
var deepCopyObj = jQuery.extend(true, {}, obj);
var deepCopyObj = _.cloneDeep(obj); //latest version UndescoreJs makes shallow copy
Harapan ini membantu...
Dalam menyalin objek dalam JavaScript (saya pikir yang terbaik dan paling sederhana)
1. Menggunakan JSON.mengurai(JSON.stringify(objek));
var obj = {
a: 1,
b: {
c: 2
}
}
var newObj = JSON.parse(JSON.stringify(obj));
obj.b.c = 20;
console.log(obj); // { a: 1, b: { c: 20 } }
console.log(newObj); // { a: 1, b: { c: 2 } }
2.Menggunakan diciptakan metode
function cloneObject(obj) {
var clone = {};
for(var i in obj) {
if(obj[i] != null && typeof(obj[i])=="object")
clone[i] = cloneObject(obj[i]);
else
clone[i] = obj[i];
}
return clone;
}
var obj = {
a: 1,
b: {
c: 2
}
}
var newObj = cloneObject(obj);
obj.b.c = 20;
console.log(obj); // { a: 1, b: { c: 20 } }
console.log(newObj); // { a: 1, b: { c: 2 } }
3. Menggunakan Lo-Dash's _.cloneDeep link lodash
var obj = {
a: 1,
b: {
c: 2
}
}
var newObj = _.cloneDeep(obj);
obj.b.c = 20;
console.log(obj); // { a: 1, b: { c: 20 } }
console.log(newObj); // { a: 1, b: { c: 2 } }
4. Menggunakan Objek.menetapkan metode ()
var obj = {
a: 1,
b: 2
}
var newObj = _.clone(obj);
obj.b = 20;
console.log(obj); // { a: 1, b: 20 }
console.log(newObj); // { a: 1, b: 2 }
TAPI YANG SALAH KETIKA
var obj = {
a: 1,
b: {
c: 2
}
}
var newObj = Object.assign({}, obj);
obj.b.c = 20;
console.log(obj); // { a: 1, b: { c: 20 } }
console.log(newObj); // { a: 1, b: { c: 20 } } --> WRONG
// Note: Properties on the prototype chain and non-enumerable properties cannot be copied.
5.Menggunakan Underscore.js _.clone link Underscore.js
var obj = {
a: 1,
b: 2
}
var newObj = _.clone(obj);
obj.b = 20;
console.log(obj); // { a: 1, b: 20 }
console.log(newObj); // { a: 1, b: 2 }
TAPI YANG SALAH KETIKA
var obj = {
a: 1,
b: {
c: 2
}
}
var newObj = _.cloneDeep(obj);
obj.b.c = 20;
console.log(obj); // { a: 1, b: { c: 20 } }
console.log(newObj); // { a: 1, b: { c: 20 } } --> WRONG
// (Create a shallow-copied clone of the provided plain object. Any nested objects or arrays will be copied by reference, not duplicated.)
JSBEN.CH Performance Benchmarking Bermain 1~3 http://jsben.ch/KVQLd
Berikut ini's versi ConroyP's jawaban atas yang bekerja bahkan jika konstruktor memiliki parameter yang diperlukan:
//If Object.create isn't already defined, we just do the simple shim,
//without the second argument, since that's all we need here
var object_create = Object.create;
if (typeof object_create !== 'function') {
object_create = function(o) {
function F() {}
F.prototype = o;
return new F();
};
}
function deepCopy(obj) {
if(obj == null || typeof(obj) !== 'object'){
return obj;
}
//make sure the returned object has the same prototype as the original
var ret = object_create(obj.constructor.prototype);
for(var key in obj){
ret[key] = deepCopy(obj[key]);
}
return ret;
}
Fungsi ini juga tersedia dalam saya simpleoo perpustakaan.
Edit:
Berikut ini's versi yang lebih kuat (terima kasih kepada Justin McCandless ini sekarang mendukung siklik referensi juga):
/**
* Deep copy an object (make copies of all its object properties, sub-properties, etc.)
* An improved version of http://keithdevens.com/weblog/archive/2007/Jun/07/javascript.clone
* that doesn't break if the constructor has required parameters
*
* It also borrows some code from http://stackoverflow.com/a/11621004/560114
*/
function deepCopy(src, /* INTERNAL */ _visited, _copiesVisited) {
if(src === null || typeof(src) !== 'object'){
return src;
}
//Honor native/custom clone methods
if(typeof src.clone == 'function'){
return src.clone(true);
}
//Special cases:
//Date
if(src instanceof Date){
return new Date(src.getTime());
}
//RegExp
if(src instanceof RegExp){
return new RegExp(src);
}
//DOM Element
if(src.nodeType && typeof src.cloneNode == 'function'){
return src.cloneNode(true);
}
// Initialize the visited objects arrays if needed.
// This is used to detect cyclic references.
if (_visited === undefined){
_visited = [];
_copiesVisited = [];
}
// Check if this object has already been visited
var i, len = _visited.length;
for (i = 0; i < len; i++) {
// If so, get the copy we already made
if (src === _visited[i]) {
return _copiesVisited[i];
}
}
//Array
if (Object.prototype.toString.call(src) == '[object Array]') {
//[].slice() by itself would soft clone
var ret = src.slice();
//add it to the visited array
_visited.push(src);
_copiesVisited.push(ret);
var i = ret.length;
while (i--) {
ret[i] = deepCopy(ret[i], _visited, _copiesVisited);
}
return ret;
}
//If we've reached here, we have a regular object
//make sure the returned object has the same prototype as the original
var proto = (Object.getPrototypeOf ? Object.getPrototypeOf(src): src.__proto__);
if (!proto) {
proto = src.constructor.prototype; //this line would probably only be reached by very old browsers
}
var dest = object_create(proto);
//add this object to the visited array
_visited.push(src);
_copiesVisited.push(dest);
for (var key in src) {
//Note: this does NOT preserve ES5 property attributes like 'writable', 'enumerable', etc.
//For an example of how this could be modified to do so, see the singleMixin() function
dest[key] = deepCopy(src[key], _visited, _copiesVisited);
}
return dest;
}
//If Object.create isn't already defined, we just do the simple shim,
//without the second argument, since that's all we need here
var object_create = Object.create;
if (typeof object_create !== 'function') {
object_create = function(o) {
function F() {}
F.prototype = o;
return new F();
};
}
Crockford menunjukkan (dan saya sukai) menggunakan fungsi ini:
function object(o) {
function F() {}
F.prototype = o;
return new F();
}
var newObject = object(oldObject);
It's terse, bekerja seperti yang diharapkan dan anda don't membutuhkan perpustakaan.
EDIT:
Ini adalah polyfill untuk Objek.membuat
, sehingga anda juga dapat menggunakan ini.
var newObject = Object.create(oldObject);
CATATAN: Jika anda menggunakan ini, anda mungkin memiliki masalah dengan beberapa iterasi yang menggunakan hasOwnProperty
. Karena, membuat
buat baru kosong objek yang mewarisi oldObject
. Tapi itu masih berguna dan praktis untuk kloning benda-benda.
Untuk contoh jika oldObject.a = 5;
newObject.a; // is 5
tapi:
oldObject.hasOwnProperty(a); // is true
newObject.hasOwnProperty(a); // is false