Rohit
Rohit

Reputation: 6613

Clone an object with closure

I'm trying to clone an object with closures. Tried angular.copy()

function Foo() {
  var data;

  this.x = function(val) {
    if (val) {
      data = val;
    }
    return data;
  }
}

var a = new Foo();
var b = angular.copy(a);

b.x(); // undefined
a.x(5); // set x
b.x(); // 5. expected undefined

Upvotes: 0

Views: 231

Answers (1)

Jan
Jan

Reputation: 5815

You could create your own clone method on your Foo object if you'd like. You'd just have to make sure to clone any relevant data too (if data f.e. is an object the method below would just store a reference to the same object).

function Foo() {
  var data;

  this.x = function(val) {
    if (val) {
      data = val;
    }
    return data;
  }
  this.clone = function() {
    var n = new Foo();
    n.x(data);
    return n;
  }
}

var a = new Foo();
var b = a.clone();

a.x(5); // set x
console.log("a.x: " + a.x()); // 5
console.log("b.x: " + b.x()); // undefined

Upvotes: 1

Related Questions