gpt4 book ai didi

javascript - 如何从类中隐藏构造函数之外的方法也被返回?

转载 作者:行者123 更新时间:2023-11-30 19:16:16 33 4
gpt4 key购买 nike

我是新来的类(class),我有这段代码:

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 和现在返回的对象,我认为 private 会起作用:

{
created_on: '2019-09-16T16:26:49.885Z',
name: 'UPDATED CREATE BOARD TEST',
threads: [],
updated_on: '2019-09-16T16:26:49.885Z',
_id: 'c8ebf4d0-d89e-11e9-81ae-1dc34f066a52',
delete_password: 'abcd123',
loading: [Object],
error: [Object],
genUuidV1: [Function],
now: [Function]
}

我不想要那个 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: ''
};
}
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();

关于javascript - 如何从类中隐藏构造函数之外的方法也被返回?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57961020/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com