Skip to content

Instantly share code, notes, and snippets.

@XoseLluis
Created August 23, 2020 10:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save XoseLluis/e01e9c2e944f462585921bcd762168fe to your computer and use it in GitHub Desktop.
Save XoseLluis/e01e9c2e944f462585921bcd762168fe to your computer and use it in GitHub Desktop.
Method Composition in JavaScript
function composeMethods(...methods){
//use a normal function, not an arrow, as we need "dynamic this"
return function(...args) {
methods.forEach(method => {
let methodArgs = args.splice(0, method.length);
method.call(this, ...methodArgs);
})
}
}
class Particle{
constructor(x, y, opacity){
this.x = x || 0;
this.y = y || 0;
this.opacity = 1;
}
move(x, y){
this.x += x;
this.y += y;
}
fade(v){
this.opacity += v;
}
}
//composing "move" and "fade" and adding it as a new "moveAndFade" method
Particle.prototype.moveAndFade = composeMethods(Particle.prototype.move, Particle.prototype.fade);
let p1 = new Particle();
console.log(JSON.stringify(p1));
//x, y, v
p1.moveAndFade(4, 8, -0.1);
console.log(JSON.stringify(p1));
p1.moveAndFade(2, 3, -0.2);
console.log(JSON.stringify(p1));
// {"x":0,"y":0,"opacity":1}
// {"x":4,"y":8,"opacity":0.9}
// {"x":6,"y":11,"opacity":0.7}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment