【问题标题】:display is not a function显示不是功能
【发布时间】: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>
    );
  }
}

【问题讨论】:

  • &lt;Employee&gt;cloned 实际上并没有使对象成为Employee 的实例,您需要在某处执行new Employee(...)
  • 我从这里提取样本并进行了改编:mertarauh.com/tutorials/typescript-design-patterns/…
  • 原型模式的目标是避免实例化新对象,而是克隆它们
  • 如果这是您要复制的内容,请注意您错过了 prototype 属性访问权限...

标签: reactjs typescript


【解决方案1】:

你可以试试这个:

    clone():Employee {
        return Object.assign(Object.create(Object.getPrototypeOf(Employee)), this)
    }

这将基于当前对象类创建一个新对象,同时还使用您之前拥有的数据填充数据。

您的解决方案实际上并未将其设为 Employee,因为它只是一个克隆的普通对象。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2018-07-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-15
  • 2019-09-04
  • 2017-11-21
  • 2012-01-27
相关资源
最近更新 更多