2017-08-28 27 views
0

如何导出不带函数的对象?ES6如何导出不带函数的对象

用户模型:

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 } 
+0

什么是“insert”?为什么你需要导出时,你已经把它作为'用户'属性? – estus

+0

@estus抱歉,结果实际上是正确的。我误解了。 – laukok

+0

如果该方法在对象上不可用,用户应该如何调用'user.insert'? –

回答

1

您可以使用ES6类而不是使用对象。你可以找到一个例子here

// 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 
} 
+0

您可以向该类添加'toJson()'函数并返回一个字符串化的JSON对象,或者您可以根据需要返回一个新对象以像console.log(result.toJson());'那样打印它。我在编辑我的答案。 – bennygenel