Run
Run

Reputation: 57176

ES6 how to export object without its functions

How do I export an object without its functions?

A user model:

export default {
  data: {},

  sanitize (options) {
  },

  async insert (options) {
  },

  async find (options) {
  },

  async remove (options) {
  }
}

usage:

const result = await user.insert({ id: '123', name: 'haha xxxx', password: 'gskgsgjs' })
console.log(user)

result:

{ data: { id: '123', name: 'haha', _id: 59a40e73f63b17036e5ce5c4 },
  sanitize: [Function: sanitize],
  insert: [Function: insert],
  find: [Function: find],
  remove: [Function: remove] }

What I am after:

{ data: { id: '123', name: 'haha', _id: 59a40e73f63b17036e5ce5c4 }

Any ideas?

EDIT:

Using ES6 class:

export default class User {
  constructor(options) {
    this.data = this.sanitize(options)
  }

  sanitize (options) {
  }

  async insert (options) {
  }

  async find (options) {
  }

  async remove (options) {
  }
}

Usage:

  let User =  new user()
  // Inject a doc.
  const result = await User.insert({ id: '123', name: 'haha xxxx', password: 'gskgsgjs' })
  console.log(User)

Result:

User {
  data: { id: '123', name: 'haha xxxx', _id: 59a4143e63f3450e2e0c4fe4 } }

Still, not exactly what I am after:

{ data: { id: '123', name: 'haha', _id: 59a40e73f63b17036e5ce5c4 }

Upvotes: 0

Views: 223

Answers (1)

bennygenel
bennygenel

Reputation: 24660

You can use ES6 classes rather than using an object. You can find an example 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
}

Upvotes: 1

Related Questions