Reputation: 336
I wanted to clone original object and function without reference, is my code consider the correct way to clone object and function?
var apple = new function() {
this.type = "macintosh";
this.color = "red";
}
function aaa() {
return this.color + ' ' + this.type + ' apple';
};
var a = JSON.parse(JSON.stringify(apple))
var b =
JSON.parse(JSON.stringify(apple));
console.log(a)
a.getInfo = aaa
b.getInfo = aaa
a.color='green' // only a is green color
console.log(a.getInfo())
console.log(b.getInfo())
Upvotes: 2
Views: 158
Reputation: 4786
Try this function:
var clone = function (object) {
// Copy everything that is not an object
if (object == null || typeof(object) !== 'object') {
return object
}
// Calling constructor
var temp = new object.constructor()
// Recursively cloning children
for (var key in object) {
temp[key] = clone(object[key])
}
return temp
}
Test:
var test = { a: 0, b: function () { console.log(1) } }
var cloned = clone(test)
https://jsfiddle.net/feshcdLe/1/
Upvotes: 1
Reputation: 106
For cloning objects, you can use Object.assign
and set the first argument as an empty object.
For example
const clone = Object.assign({}, apple.call({}));
const result = aaa.call(clone);
console.log(result);
//=> red macintosh apple;
I made use of Function.call
here simply because I don't know if you meant to access the global this
or a different scope or what. If you do know what your this
is referring to, then you can simply do.
const clone = Object.assign({}, this);
const result = aaa();
console.log(result);
Upvotes: 0