Skip to content

Instantly share code, notes, and snippets.

@StevenLangbroek
Last active May 3, 2019 20:05
Show Gist options
  • Save StevenLangbroek/daf6391e6e2bdef801c6 to your computer and use it in GitHub Desktop.
Save StevenLangbroek/daf6391e6e2bdef801c6 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;
}
}
@mlippert
Copy link

mlippert commented Aug 23, 2016

I really like this design for private instance variables. I just have one question about the above, how is this.defaults defined?

Perhaps you meant Model.defaults, where the Model.defaults property is defined after the Model class?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment