【发布时间】:2019-01-13 01:16:00
【问题描述】:
我正在尝试在 Sharepoint Framework 小示例中实现原型模式,我从这里获取示例:
https://mertarauh.com/tutorials/typescript-design-patterns/prototype-pattern/
并改编如下:
class Employee {
private totalperMonth: number;
constructor(public name: string, public hiredDate: Date, public 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>
);
}
}
但是我在控制台中遇到了这个错误:
我错过了什么?
【问题讨论】:
-
我不习惯 sharepoint 框架,但是在使用 Jest 进行测试时,我在处理不变性方面遇到了一些麻烦。就我而言,使用 Object.defineProperty 可以解决这个问题:developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
-
你是否在任何地方定义了 name 变量?
标签: reactjs typescript