Javascript:使用Object.assign克隆实例时的成员方法错误

时间:2018-01-22 21:21:38

标签: javascript ecmascript-6 creation cloning

我是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 ();

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

提前非常感谢你!

2 个答案:

答案 0 :(得分:2)

  

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

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

答案 1 :(得分:0)

要克隆对象,您还需要使用相同的原型对象 - 不要只将克隆对象的属性分配给{}

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

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