如何导出没有其功能的对象?
用户模型:
export default {
data: {},
sanitize (options) {
},
async insert (options) {
},
async find (options) {
},
async remove (options) {
}
}
用法:
const result = await user.insert({ id: '123', name: 'haha xxxx', password: 'gskgsgjs' })
console.log(user)
结果:
{ data: { id: '123', name: 'haha', _id: 59a40e73f63b17036e5ce5c4 },
sanitize: [Function: sanitize],
insert: [Function: insert],
find: [Function: find],
remove: [Function: remove] }
我所追求的:
{ data: { id: '123', name: 'haha', _id: 59a40e73f63b17036e5ce5c4 }
有什么想法吗?
编辑:
使用 ES6 类:
export default class User {
constructor(options) {
this.data = this.sanitize(options)
}
sanitize (options) {
}
async insert (options) {
}
async find (options) {
}
async remove (options) {
}
}
用法:
let User = new user()
// Inject a doc.
const result = await User.insert({ id: '123', name: 'haha xxxx', password: 'gskgsgjs' })
console.log(User)
结果:
User {
data: { id: '123', name: 'haha xxxx', _id: 59a4143e63f3450e2e0c4fe4 } }
不过,不完全是我所追求的:
{ data: { id: '123', name: 'haha', _id: 59a40e73f63b17036e5ce5c4 }
您可以使用 ES6 类而不是使用对象。您可以在此处找到示例。
// A base class is defined using the new reserved 'class' keyword
class Polygon {
// ..and an (optional) custom class constructor. If one is
// not supplied, a default constructor is used instead:
// constructor() { }
constructor(height, width) {
this.name = 'Polygon';
this.height = height;
this.width = width;
}
// Simple class instance methods using short-hand method
// declaration
sayName() {
ChromeSamples.log('Hi, I am a ', this.name + '.');
}
sayHistory() {
ChromeSamples.log('"Polygon" is derived from the Greek polus (many) ' +
'and gonia (angle).');
}
// Method to get json string
toJson() {
return JSON.stringify({ name: this.name, height: this.height, weight: this.weight });
}
// We will look at static and subclassed methods shortly
}