您将从我的问题中看到,我是TypeScript / JavaScript的新手。我正在开发使用IndexedDB的Blazor Wasm应用程序。我注意到有两种(无疑还有更多)方法可以为数据库的存储创建对象。我想知道哪种方法比另一种方法更有利。显然,函数方法要简洁得多。但是从概念上讲,类方法似乎更好。
class myObject
{
_property1: string;
_property2: number;
constructor(parm1, parm2)
{
this.property1 = parm1;
this.property2 = parm2;
}
get property1() { return this._property1; }
set property1(value1) { this._property1 = value1; }
get property2() { return this._property2; }
set property2(value2) { this._property2 = value2; }
}
function myObject(parm1, parm2)
{
return { property1: parm1, property2: parm2 };
}
类是可序列化的,但这样做会删除函数。要在读取后重新创建类,您需要将每个读取操作加倍。 indexedDB将以非类的形式加载数据,然后您需要创建类,然后使用Object.assign
之类的数据将其复制到类成员中。只要您在任何地方都使用function.call
样式语法,就可以摆脱副本,但是如果方法访问this
,即使这样做也会出现问题。
这是一个巨大的混乱。只是不要这样做。只需使用简单的对象即可,例如“数据”。
[其他语言具有很好的高效工具,可以像反序列化一样将序列化的数据强制返回到类中。 Javascript没有。通过在JavaScript中进行此类读/写操作,您完成的所有工作都会使程序不必要地变慢。
function loadObject(db: IDBDatabase, id: number) {
return new Promise((resolve, reject) => {
const txn = db.transaction('store');
const store = txn.objectStore('store');
const request = store.get(id);
request.onsuccess = event => resolve(event.target.result);
request.onerror = event => reject(event.target.error);
});
}
interface MyObject {
id: number;
_property1: string;
_property2: number;
}
function isMyObject(value: any): value is MyObject {
return typeof values === 'object' && value !== null &&
Number.isInteger(value.id) and typeof value._property1 === 'string'
&& 'etc...';
}
async function loadObjectWithTypeAssertion(db, id) {
// Load object as type 'any'
const object = await loadObject(db, id);
// Prove to the typescript compiler that the 'any' type
// is in fact an instance of the 'MyObject' type
if (!isMyObject(object)) {
throw new Error('object loaded from db is not type MyObject');
}
// At this point because we are after the type assertion call,
// object is now type "MyObject" in intellisense
// Thefore the return type of this async function is now
// Promise<MyObject>
return object;
}
仍然在前面的示例中伪装功能。
class MyObject() {
private _property1: string;
private _property2: number;
}
async function loadAndAssign(...) {
const object = loadObject(...);
// Create an empty instance of MyObject
const myObject = new MyObject();
// Copy the data loaded from db into the instance
Object.assign(myObject, object);
// Now the "myObject" instance has props
return myObject;
}