【问题标题】:Javascript: member method error when cloning an instance with Object.assignJavascript:使用 Object.assign 克隆实例时出现成员方法错误
【发布时间】:2018-01-22 21:21:38
【问题描述】:

我是一个 JS 新手,我一直在使用 create() 和 assign() 进行对象创建和克隆,遇到以下错误:

let Student = {
  first_name : '',
  last_name : '',
  major : '',
  IsNotSet : function () {
    return (this.first_name == '') 
        && (this.last_name == '') 
        && (this.major == '');
  },
  PrintDetails : function () {
    if (this.IsNotSet ()) {
      console.log ('Student is not set. Information cannot be retrieved.');
    } else {
      console.log ('Student Information:'
        + '\nFirst Name: ' + this.first_name
        + '\nLast Name: ' + this.last_name
        + '\nMajor: ' + this.major
      );
    }
  }
};

let StudentWithMinor = Object.assign ({}, Student,
  {
    minor : '',
    IsNotSet : function () {
      return (Student.IsNotSet.bind (this))() && (this.minor == '');
    },
    PrintDetails : function () {
      (Student.PrintDetails.bind (this))();
      if (!this.IsNotSet ()) {
        console.log ('Minor: ' + this.minor);
      }
    }
  }
);

let first_student = Object.create (Student);
first_student.first_name = 'Andrea';
first_student.last_name = 'Chipenko';
first_student.major = 'B.S.E Computer Engineering';
first_student.PrintDetails ();

let second_student = Object.assign ({}, Student);
second_student.first_name = 'Enzo';
second_student.last_name = 'D\'Napolitano';
second_student.major = 'B.S. Computer Science';
second_student.PrintDetails ();


let third_student = Object.create (StudentWithMinor);
third_student.first_name = 'Kumar';
third_student.last_name = 'Patel';
third_student.major = 'B.A. Business Administration';
third_student.minor = 'Criminal Justice';
third_student.PrintDetails ();

let fourth_student = Object.assign ({}, third_student);
// The following line is problematic
fourth_student.PrintDetails ();

我不太确定为什么最后一行会出错。那里的任何专家都可以让我了解内部发生的情况吗?

非常感谢您!

【问题讨论】:

  • 错误是什么?
  • @trincot 它们没有被复制不是因为它们不是“可枚举的”,而是因为它们属于原型。 console.log(Object.keys(Object.getPrototypeOf(third_student)))。 “Object.assign 不复制方法” --- 这是错误的,因为 Object.assign 不区分值的类型。

标签: javascript ecmascript-6 creation cloning


【解决方案1】:

Object.assign() 方法用于复制所有的值 从一个或多个源对象到目标的可枚举拥有属性 目的。它将返回目标对象。

由于third_student.PrintDetails不是它自己的属性(它属于它的原型),所以它没有被复制。

【讨论】:

  • 啊,我明白了。我认为 'Student' 和 'first_student' 将是相同的,因为它们都是 typeof () == 对象。无论如何,非常感谢你这个有见地的回答:D
【解决方案2】:

要克隆一个对象,还需要使用相同的原型对象——不要只将克隆对象的自身属性赋值给{}

let fourth_student = Object.assign(Object.create(StudentWithMinor), third_student);

let fourth_student = Object.assign(Object.create(Object.getPrototypeOf(third_student)),
                                   third_student);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-17
    • 2015-09-28
    • 1970-01-01
    • 2018-01-30
    • 2014-06-07
    • 1970-01-01
    • 2012-05-22
    相关资源
    最近更新 更多