用函数克隆对象

时间:2017-07-25 10:06:36

标签: javascript

我想在没有引用的情况下克隆原始对象和函数,我的代码是否考虑克隆对象和函数的正确方法?

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())

2 个答案:

答案 0 :(得分:0)

尝试此功能:

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
}

测试:

var test = { a: 0, b: function () { console.log(1) } }
var cloned = clone(test)

https://jsfiddle.net/feshcdLe/1/

答案 1 :(得分:0)

对于克隆对象,可以使用Object.assign并将第一个参数设置为空对象。 例如

const clone = Object.assign({}, apple.call({}));
const result = aaa.call(clone);
console.log(result);
//=> red macintosh apple;

我在这里使用Function.call只是因为我不知道你是想要访问全局this还是不同的范围或什么。如果您 知道this所指的内容,那么您就可以这样做。

const clone = Object.assign({}, this);
const result = aaa();
console.log(result);

MDN Object.assign

MDN Function.call

相关问题