【发布时间】:2019-06-07 06:30:27
【问题描述】:
我有一个带有显示功能的员工类,然后在尝试实现原型模式时,尝试使用克隆对象中的显示功能时出错。
员工类代码:
类员工{
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>
);
}
}
【问题讨论】:
-
<Employee>cloned实际上并没有使对象成为Employee的实例,您需要在某处执行new Employee(...)。 -
我从这里提取样本并进行了改编:mertarauh.com/tutorials/typescript-design-patterns/…
-
原型模式的目标是避免实例化新对象,而是克隆它们
-
如果这是您要复制的内容,请注意您错过了
prototype属性访问权限...
标签: reactjs typescript