-
-
Save vothanhkiet/45a3fe227062fdd7cd8e to your computer and use it in GitHub Desktop.
Private variables in ES6 Classes.
This file contains 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 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