Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

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
You can’t perform that action at this time.