ES6如何在没有其功能的情况下导出对象

时间:2017-08-28 12:50:26

标签: model ecmascript-6 export

如何在没有其功能的情况下导出对象?

用户模型:

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 }

1 个答案:

答案 0 :(得分: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
}
相关问题