如何从类也返回构造函数中隐藏方法?

时间:2019-09-16 16:32:15

标签: javascript typescript

我是班上的新手,我有以下代码:

nested_abc

此创建的对象的问题在于它还包括genUuidV1方法,现在在返回的对象上,我认为私有方法可以工作:

class BoardTypeResponse {
  created_on: string;
  name: string;
  threads: string[];
  updated_on: string;
  _id: string;
  delete_password: string;
  loading: BoardLoadingType;
  error: BoardErrorType;

  constructor(params: {
    name?: string;
    delete_password?: string;
    _id?: string;
  }) {
    this.created_on = this.now();
    this.name = params.name || 'TEST BOARD NAME';
    this.threads = [];
    this.updated_on = this.now();
    this._id = params._id || this.genUuidV1();
    this.delete_password = params.delete_password || this.genUuidV1();
    this.loading = {
      update_name: false
    };
    this.error = {
      update_name: ''
    };
  }
  private genUuidV1 = () => uuidv1();
  private now = () => new Date().toISOString();
}

我不想要那个genUuidV1,现在看到了,我如何隐藏它回来?

1 个答案:

答案 0 :(得分:1)

编写自定义返回方法

class BoardTypeResponse {
    created_on: string;
    name: string;
    threads: string[];
    updated_on: string;
    _id: string;
    delete_password: string;
    loading: BoardLoadingType;
    error: BoardErrorType;

    constructor(params: {
        name ? : string;
        delete_password ? : string;
        _id ? : string;
    }) {
        (this.created_on = this.now()),
        (this.name = params.name || 'TEST BOARD NAME'),
        (this.threads = []),
        (this.updated_on = this.now()),
        (this._id = params._id || this.genUuidV1()),
        (this.delete_password = params.delete_password || this.genUuidV1()),
        (this.loading = {
            update_name: false
        });
        this.error = {
            update_name: ''
        };
    }
    genUuidV1 = () => uuidv1();
    now = () => new Date().toISOString();
    getObject = () => {
        return {
            created_on: this.created_on,
            name: this.name,
            threads: this.threads,
            updated_on: this.updated_on,
            _id: this._id,
            delete_password: this.delete_password,
            loading: this.loading,
            error: this.error,
        };
    };
}

用法:

致电 getObject()

let obj = new BoardTypeResponse();
let y = obj.getObject();