如何使用javascript中的代理模式-创新互联
                                            这篇文章主要讲解了如何使用javascript中的代理模式,内容清晰明了,对此有兴趣的小伙伴可以学习一下,相信大家阅读完之后会有帮助。

介绍:代理使我们很常见的一众模式,proxy,nginx都称之为代理,代理是什么意思呢?代理模式在客户端和目标对象之间加入一个新的代理对象,代理对象起到一个中介作用,去掉客户不能看到的内容和服务,或者增添客户需要的额外服务。
定义:给某一个对象提供一个代理,并由代理对象控制对原对象的引用。代理模式是一种对象结构型模式。
场景:我们还是以画图形为例,我将所有的绘图动作包装到Shape类中,使用代理模式来部分开放功能给客户。
示例:
var Shape = function(color){
  console.log('创建了一个对象');
  this.color = color;
  this.x;
  this.y;
  this.radius;
 
  this.setAttr = function(x, y, radius){
    this.x = x;
    this.y = y;
    this.radius = radius;
  }
  this.drawCircle = function(){
    console.log('画圆: 颜色:' + this.color + ' x:' + this.x + ' y:' + this.y + ' radius:' + this.radius)
  }
  this.drawSquare = function(){
    console.log('画方: 颜色:' + this.color + ' x:' + this.x + ' y:' + this.y )
  }
  this.drawTriangle = function(){
    console.log('画三角: 颜色:' + this.color + ' x:' + this.x + ' y:' + this.y )
  }
}
 
var proxyShape = function(color, x, y, radius){
  this.color = color;
  this.x = x;
  this.y = y;
  this.radius = radius;
  this.shape = null;
  this.drawSquare = function(){
    if(this.shape === null){
      this.shape = new Shape(this.color);
      this.shape.setAttr(this.x, this.y, this.radius);
    }
    this.shape.drawSquare();
  }
}
 
var square = new proxyShape('red', 10, 10);
square.drawSquare();
square.drawSquare();
// 创建了一个对象
// 画方: 颜色:red x:10 y:10
// 画方: 颜色:red x:10 y:10                                                分享题目:如何使用javascript中的代理模式-创新互联
浏览路径:http://www.scyingshan.cn/article/dgpici.html

 建站
建站
 咨询
咨询 售后
售后
 建站咨询
建站咨询 
 