Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/416.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 例如,这是一种战略模式吗?_Javascript_Oop_Design Patterns - Fatal编程技术网

Javascript 例如,这是一种战略模式吗?

Javascript 例如,这是一种战略模式吗?,javascript,oop,design-patterns,Javascript,Oop,Design Patterns,正如主题本身所说,这是Javascript中的策略模式示例吗 (我认为这个问题更适合codereview,但他们在stackoverflow上重定向了我) var canvas={ 上下文:document.getElementById(“画布”).getContext(“2d”) }; /////////////////////////////////////////////////// 功能广场(_策略){ 这个x=50; 这个y=50; 这个宽度=100; 这个高度=100; this.s

正如主题本身所说,这是Javascript中的策略模式示例吗

(我认为这个问题更适合codereview,但他们在stackoverflow上重定向了我)

var canvas={
上下文:document.getElementById(“画布”).getContext(“2d”)
};
///////////////////////////////////////////////////
功能广场(_策略){
这个x=50;
这个y=50;
这个宽度=100;
这个高度=100;
this.strategy=\u策略;
}
Square.prototype.draw=函数(){
这个.战略(这个),;
};
///////////////////////////////////////////////////
功能圈(策略){
打电话(这个,策略);
这个半径=25;
}
Circle.prototype=new Square();
///////////////////////////////////////////////////
函数drawSquare(形状){
canvas.context.strokeRect(shape.x,shape.y,shape.width,shape.height);
}
///////////////////////////////////////////////////
函数绘制圆(形状){
canvas.context.beginPath();
canvas.context.arc(shape.x,shape.y,shape.radius,0,360,false);
canvas.context.stroke();
}
///////////////////////////////////////////////////
变量形状=[];
推(新正方形(drawSquare));
推(新圆圈(drawCircle));

对于(var i=0;i是的,但这种模式可以在Javascript中实现得非常简单,甚至可能不是一种模式

基本上,即使是这样:

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);
};
您只需执行以下操作:

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

顺便说一句,不要让你的类引用全局变量。将其作为属性或参数。

如果你拒绝投票,请至少留下解释…我没有拒绝投票,但这个问题没有显示出任何努力,也没有显示出对主题的任何理解。你基本上发布了一堆代码并说:“对还是错,这使用的是模式X”。我认为这不是代码的“墙”,示例只需几分钟就可以回顾。无论如何,谢谢你的建议。你是对的:“代码的墙”有点苛刻。就像我说的,我没有投反对票。你读过与反对票一起出现的工具提示吗?它以“这个问题没有显示任何研究成果”开头“好吧,你认为这个问题确实表明了研究的努力吗?
var a = new Square();
a.draw = function(canvas) {
    canvas.context.strokeRect(this.x + 5, this.y, this.width, this.height);
};