【问题标题】:How to copy object methods in ES6如何在 ES6 中复制对象方法
【发布时间】:2019-11-17 05:59:27
【问题描述】:

我想使用扩展运算符克隆一个对象。但是,方法并没有如图所示复制

我知道你可以做 Object.Assign() 但我正在寻找一种使用 ES6 语法的方法

Deep copy in ES6 using the spread syntax 的解决方案涉及深度克隆:我只对复制方法和属性感兴趣

How to clone a javascript ES6 class instance 的解决方案使用了 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]

【问题讨论】:

标签: javascript cloning


【解决方案1】:

这个:

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

【讨论】:

    【解决方案2】:

    我认为你可以这样做:

    class Test {
      toString() {
        return "This is a test object";
      }
    }
    
    let test = new Test();
    let test2 = {};
    
    test2.__proto__ = test.__proto__;
    
    console.log(String(test));
    console.log(String(test2));
    

    但我不知道,也许这是一种不好的做法:/..

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-08
      • 1970-01-01
      相关资源
      最近更新 更多