【发布时间】: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