如何在ES6中复制对象方法

用户名

我想使用传播运算符克隆一个对象。但是,方法未如所示复制

我知道您可以做Object.Assign(),但是我正在寻找一种使用ES6语法来做到这一点的方法

使用传播语法的ES6深度复制中的解决方案涉及深度克隆:我只对复制方法和属性感兴趣

如何克隆JavaScript ES6类实例中的解决方案利用Object.Assign()

class Test {
  toString() {
    return "This is a test object";
  }
}

let test = new Test();
let test2 = { ...test };

console.log(String(test));
console.log(String(test2));

// Output: This is a test object
// Output: [object Object]
微笑

这个:

class Test {
  toString() {
    return "This is a test object";
  }
} 

严格来讲,没有定义任何对象方法而是定义类方法。

您需要将方法作为“自己的属性”直接附加到对象上,以便传播以复制它们:

class Test {
  constructor() {
    // define toString as a method attached directly to
    // the object
    this.toString = function() {
      return "This is a test object";
    }
  }
}

let test = new Test();
let test2 = { ...test };

console.log(String(test));
console.log(String(test2));

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章