javascript - Example, is this strategy pattern? -


as topic itself, example of strategy pattern in javascript?

(i think question more suitable codereview redirect me on stackoverflow)

var canvas = {     context:  document.getelementbyid("canvas").getcontext("2d") }; /////////////////////////////////////////////////// function square(_strategy) {     this.x = 50;     this.y = 50;     this.width = 100;     this.height = 100;      this.strategy = _strategy; }  square.prototype.draw = function() {     this.strategy(this); }; /////////////////////////////////////////////////// function circle(strategy) {     square.call(this, strategy);      this.radius = 25; }  circle.prototype = new square(); /////////////////////////////////////////////////// function drawsquare(shape) {     canvas.context.strokerect(shape.x, shape.y, shape.width, shape.height); } /////////////////////////////////////////////////// function drawcircle(shape) {     canvas.context.beginpath();     canvas.context.arc(shape.x , shape.y, shape.radius, 0, 360, false);     canvas.context.stroke(); } /////////////////////////////////////////////////// var shapes = []; shapes.push(new square(drawsquare)); shapes.push(new circle(drawcircle));  for(var i=0; i<shapes.length; i++) {     shapes[i].draw(); } 

live example

i know don't need width , height drawing circle. (i need them later selecting circle, not mistake :) )

yes, such pattern can implemented trivially in javascript it's not pattern.

basically if had this:

function square() {     this.x = 50;     this.y = 50;     this.width = 100;     this.height = 100; }  square.prototype.draw = function(canvas) {     canvas.context.strokerect(this.x, this.y, this.width, this.height); }; 

you can do:

var = new square(); a.draw = function(canvas) {     canvas.context.strokerect(this.x + 5, this.y, this.width, this.height); }; 

btw, not make classes refer global variables. take property or parameter.


Comments

Popular posts from this blog

java - Run a .jar on Heroku -

java - Jtable duplicate Rows -

validation - How to pass paramaters like unix into windows batch file -