2017-08-28 28 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