I have some trouble in making a callback on an object method. Here is a very simplified example. I create a class Point2D with three methods (constructor, translate, dump). I create an array with two such elements inside. Now I want to create an "iterate" function which takes as parameters the address of a callback method and two parameters. I don't know if this is possible and, if yes, what is the syntax to write my "iterate" function. If somebody can help...
<!DOCTYPE html>
<html lang="fr" >
<head><meta charset="utf-8"></head>
<body>
<script>
class Point2D {
constructor (x, y) {this.x = x ; this.y = y ; }
translate (dx, dy) {this.x += dx ; this.y += dy ; }
dump () {alert ("point : " + this.x + ", " + this.y) ; }
}
function iterate (callBack, p1, p2) {
// Do something (callBack) on all elements, with parameters
for (var i = 0 ; i <= 1 ; i++) points[i].callBack (p1, p2) ;
}
var points = new Array () ;
points.push (new Point2D (10, 10)) ;
points.push (new Point2D (20, 20)) ;
// Here is what I would like to do
iterate (dump) ; // dump points before translate
iterate (translate, 5, 5) ;
iterate (dump) ; // dumps points after translate
</script>
</body>
</html>
Array, so you can usemapandforEachetc.points.forEach(p => p.dump()),points.forEach(point => p.translate(5, 5)), etc I'd argue that this is also easier to understand.