Last active
          May 3, 2019 20:05 
        
      - 
      
- 
        Save StevenLangbroek/daf6391e6e2bdef801c6 to your computer and use it in GitHub Desktop. 
    Private variables in ES6 Classes.
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | /** | |
| * 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); | |
| } | |
| } | 
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | 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
  
            
I really like this design for private instance variables. I just have one question about the above, how is
this.defaultsdefined?Perhaps you meant
Model.defaults, where theModel.defaultsproperty is defined after the Model class?