Skip to content

Instantly share code, notes, and snippets.

@hellowin
Last active August 29, 2015 14:21
Show Gist options
  • Select an option

  • Save hellowin/f89febd25e07ae17e02c to your computer and use it in GitHub Desktop.

Select an option

Save hellowin/f89febd25e07ae17e02c to your computer and use it in GitHub Desktop.
Javascript Copy Object Reference
// using constructor to clone object
var A = function(){
this.array = ['a','b','c'];
};
var a = new A();
console.log(a.array);
// ["a", "b", "c"]
var b = new A();
b.array.push('d');
console.log(b.array);
// ["a", "b", "c", "d"]
// using function factory to clone object
var factoryA = function(){
return ['a','b','c'];
};
var a = factoryA();
console.log(a);
// ["a", "b", "c"]
var b = factoryA();
b.push('d');
console.log(b);
// ["a", "b", "c", "d"]
// most easy way to clone object
var a = ['a','b','c'];
var b = JSON.parse(JSON.stringify(a));
b.push('d');
console.log(a);
// ["a", "b", "c"]
console.log(b);
// ["a", "b", "c", "d"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment