javascript开发中的封装模式(转)

时间:2023-03-08 19:51:57
  var bgAuido={
audio : pingfan.$$('audio'),
audioBtn : pingfan.$$('audioBtn'),
init : function(){
   var _this=this;
   window.addEventListener(touchStart,function(){
     _this.audio.play();
     window.removeEventListener(touchStart,arguments.callee)
9       },false);
  this.audioBtn.addEventListener(touchStart,function(){
       if(_this.audioBtn.className.replace(/(^\s+)|(\s+$)/g,'')=='off'){
          _this.audio.play();
          _this.audioBtn.className='';
       }else if(_this.audioBtn.className==''){
           _this.audio.pause();
          _this.audioBtn.className='off';
       }
   },false) }
} bgAuido.init();

属性与方法,都通过自变量定义给对象,然后通过init()方法整体驱动,但是不方便继承,与赋值更改属性(由于属性值没有预留参数,所以,只能单个更改)。下面的方法可以很方便继承和赋予参数

 function BgAuido(opt){
opt=opt || {};
this.audio = pingfan.$$('audio'),
this.audioBtn = pingfan.$$('audioBtn'),
this.width=opt.width || ;
}
BgAuido.prototype={
say:function(){
alert(this.width);
},
init : function(){
var _this=this;
window.addEventListener(touchStart,function(){
_this.audio.play();
window.removeEventListener(touchStart,arguments.callee)
},false);
this.audioBtn.addEventListener(touchStart,function(){
if(_this.audioBtn.className.replace(/(^\s+)|(\s+$)/g,'')=='off'){
_this.audio.play();
_this.audioBtn.className='';
}else if(_this.audioBtn.className==''){
_this.audio.pause();
_this.audioBtn.className='off';
}
},false) }
}