Javascript Expost Interface Implementation
For some time i've been thinking, how can i export a JS object that will expose only public functions, yet will keep all my million functions "hidden" just to make it less messy..
The point is to create an anonymous function and create the instance within, while returning a new object with members pointing at the instance functions with ".bind" to the instance.
So here it is
The point is to create an anonymous function and create the instance within, while returning a new object with members pointing at the instance functions with ".bind" to the instance.
So here it is
let encapsulated = (function encapsulated_builder(){ let encapsulated = class encapsulated{ constructor(){ this.food = 'bamba'; this.animal = 'lion'; } addFood(f){ this.food += ' ' + f; } addFoodByAnimal(a){ switch (a){ case 'dog': this.addFood('bone'); break; case 'cat': this.addFood('fish'); break; } } addAnimal(a){ this.animal += ' ' + a; this.addFoodByAnimal(a); } printFood(){ console.log(this.food); } printAnimal(){ console.log(this.animal); } } let enc_instance = new encapsulated(); return { addAnimal : enc_instance.addAnimal.bind(enc_instance), printFood : enc_instance.printFood.bind(enc_instance), printAnimal : enc_instance.printAnimal.bind(enc_instance), } })(); encapsulated.addAnimal('dog'); encapsulated.printAnimal(); encapsulated.printFood(); encapsulated.addFood => undefined
Comments
Post a Comment