当前位置: 代码迷 >> JavaScript >> 用闭包克隆对象
  详细解决方案

用闭包克隆对象

热度:73   发布时间:2023-06-05 14:20:43.0

我正在尝试使用闭包克隆对象。 试过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); bx(); // undefined ax(5); // set x bx(); // 5. expected undefined 

如果需要,可以在Foo对象上创建自己的clone方法。 您只需要确保也克隆任何相关数据即可(如果data fe是一个对象,则下面的方法将只存储对同一对象的引用)。

 function Foo() { var data; this.x = function(val) { if (val) { data = val; } return data; } this.clone = function() { var n = new Foo(); nx(data); return n; } } var a = new Foo(); var b = a.clone(); ax(5); // set x console.log("ax: " + ax()); // 5 console.log("bx: " + bx()); // undefined 

  相关解决方案