Here is one possibility... though I had to cheat by adding the set count(value) setter. There may be a better way, but even if there is, I would use the longer form of extensible composition as it's easier to manipulate after the fact because the scope is passed on through state. But this method does demonstrate a private variable within the lexical scope of Counter.
constCounter=(count=0)=>({add:()=>(count+=1),getcount(){returncount;},// Set had to be addedsetcount(value){count=value;}});constcounter=Counter(0);counter.add();console.log(counter.count);// 1constsubtract=()=>({subtract(){this.count-=1;}});// The Subtract MixinObject.assign(counter,subtract());counter.subtract();console.log(counter.count);// 0
Here is one possibility... though I had to cheat by adding the
set count(value)
setter. There may be a better way, but even if there is, I would use the longer form of extensible composition as it's easier to manipulate after the fact because the scope is passed on through state. But this method does demonstrate a private variable within the lexical scope of Counter.Exactly what the doctor ordered! I love it, I feel this avoids the pitfalls and complexities of class-based inheritance
Here you go Adrian-Samuel, this is how to extend the counter with mixins, without having to update the original object...
This is superb! Alistair, really appreciate you taking the time and effort to demonstrate these very useful examples to me!