Skip to content

Instantly share code, notes, and snippets.

@vothanhkiet
Forked from StevenLangbroek/class.js
Created February 25, 2016 06:49
Show Gist options
  • Save vothanhkiet/45a3fe227062fdd7cd8e to your computer and use it in GitHub Desktop.
Save vothanhkiet/45a3fe227062fdd7cd8e to your computer and use it in GitHub Desktop.
Private variables in ES6 Classes.
/**
* So, obviously this is by no means a "new trick",
* but encapsulation in classes works the same as
* it does in "Modules" (IIFE pattern): You hide them
* in a scope, and define the methods that need access
* to them within that same scope. The constructor is
* as good a place as any for that.
*/
import _ from 'underscore';
import { get, set } from '../lib/state';
export default class Model {
constructor(initialState={}){
let state = _.extend({}, this.defaults, initialState);
this.get = get(state);
this.set = set(state);
}
}
export function get(state){
return function(key){
return state[key] || '';
}
}
export function set(state){
return function(key, value){
state[key] = value;
return this;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment