js桥接模式

桥接模式:在系统沿着多个维度变化的同时,又不增加复杂度并已达到解耦。

比如:鼠标移上去事件,改变背景和颜色

function g(tag){
    return document.getElementByTagName(tag);
}
var spans=g('span');
spans[0].onmouseover=function(){
    this.style.color='red';
    this.background='#eedede';
}
spans[0].onmouseout=function(){
    this.style.color='#dedede';
    this.style.background='red';
}
spans[1].onmouseover=function(){
    this.document.getElenmentByTagName('strong')[0].style.color='#dedede';
    this.document.getElenmentByTagName('strong')[0]style.background='#ddd';
}
spans[1].onmouseout=function(){
    this.document.getElenmentByTagName('strong')[0].style.color='#swswsw';
    this.document.getElenmentByTagName('strong')[0]style.background='red';
}

 提取共同点:

function changeColor(dom,color,bg){
    dom.style.color=color;
    dom.style.background=bg;
}

运用

spans[0].onmouseover=function(){
    changeColor(this,'red','#ddd');
}

多元化对象

//多维变量类
//运动单元
function Speed(x,y){
    this.x=x;
    this.y=y;
}
Speed.prototype.run=function(){
	console.log("run");
}
//着色单元
function Color(cl){
    this.color=cl;
}
Color.prototype.draw=function(){
	console.log("draw");
}
//变形单元
function Shape(sp){
    this.shape=sp;
}
Shape.prototype.change=function(){
	console.log("change");
}
//说话单元
function Speak(wd){
    this.word=wd;
    }
Speak.prototype.say=function(){
	console.log("say");
}
//创建球类
function Ball (x,y,c){
    this.speed=new Speed(x,y);
    this.color=new Color(c);
}
 Ball.prototype.init=function(){
     this.speed.run();
     this.color.draw();
}

//创建人物
function People(x,y,w){
    this.speed=new Speed(x,y);
    this.word=new Speak(w);
}
People.prototype.init=function(){
    this.speed.run();
    this.word.say();
}

//实例化人物

var p = new People(10,20,'hahah');
p.init();

 

你可能感兴趣的:(js)