我有一个带显示功能的员工类,然后尝试实现原型模式时,尝试从克隆对象中使用显示功能时出现错误。
员工班级代码:
班级员工{
private totalperMonth: number;
private name: string;
private hiredDate: Date;
public dailyRate: number;
constructor(name: string, hiredDate: Date, dailyRate: number){
this.totalperMonth = dailyRate * 20 ;
}
public display(): string{
return "Employee " + this.name + " earns per month: " + this.totalperMonth;
}
public clone():Employee{
var cloned = Object.create(Employee || null);
Object.keys(this).map((key: string) => {
cloned[key]= this[key];
});
return <Employee>cloned;
}
}
export default Employee;
组件代码:
import * as React from 'react';
import styles from './Prototype.module.scss';
import { IPrototypeProps } from './IPrototypeProps';
import { escape } from '@microsoft/sp-lodash-subset';
import Employee from './Employee';
export default class Prototype extends React.Component<IPrototypeProps, {}> {
public render(): React.ReactElement<IPrototypeProps> {
const today = new Date();
let employee1: Employee = new Employee('Luis', today, 500);
let employee2 = employee1.clone();
employee2.dailyRate = 550;
return (
<div className={ styles.prototype }>
<div className={ styles.container }>
<div className={ styles.row }>
<div className={ styles.column }>
<span className={ styles.title }>Welcome to SharePoint!</span>
<p className={ styles.subTitle }>Customize SharePoint experiences using Web Parts.</p>
<p className={ styles.description }>{escape(this.props.description)}</p>
<span className={ styles.label }>{employee1.display()}</span>
<span className={ styles.label }>{employee2.display()}</span>
</div>
</div>
</div>
</div>
);
}
}
答案 0 :(得分:1)
您可以尝试以下方法:
clone():Employee {
return Object.assign(Object.create(Object.getPrototypeOf(Employee)), this)
}
这将基于当前对象类创建一个新对象,同时还将您以前拥有的数据填充到数据中。
您的解决方案实际上并没有使其成为Employee,因为它只是一个克隆的普通对象。