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

 1  var bgAuido={
 2     audio : pingfan.$$('audio'),
 3     audioBtn : pingfan.$$('audioBtn'),
 4     init : function(){
 5           var _this=this;
 6           window.addEventListener(touchStart,function(){
 7                 _this.audio.play();
 8                 window.removeEventListener(touchStart,arguments.callee)
9       },false); 10   this.audioBtn.addEventListener(touchStart,function(){ 11        if(_this.audioBtn.className.replace(/(^s+)|(s+$)/g,'')=='off'){ 12           _this.audio.play(); 13           _this.audioBtn.className=''; 14        }else if(_this.audioBtn.className==''){ 15            _this.audio.pause(); 16           _this.audioBtn.className='off'; 17        } 18    },false) 19 20 } 21 } 22 23 bgAuido.init();

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

 1 function BgAuido(opt){
 2         opt=opt || {};
 3         this.audio = pingfan.$$('audio'),
 4         this.audioBtn = pingfan.$$('audioBtn'),
 5         this.width=opt.width || 400;
 6 }
 7 BgAuido.prototype={
 8         say:function(){
 9                 alert(this.width);
10         },
11         init : function(){
12                 var _this=this;
13                 window.addEventListener(touchStart,function(){
14                         _this.audio.play();
15                         window.removeEventListener(touchStart,arguments.callee)
16                 },false);
17                 this.audioBtn.addEventListener(touchStart,function(){
18                         if(_this.audioBtn.className.replace(/(^s+)|(s+$)/g,'')=='off'){
19                                 _this.audio.play();
20                                 _this.audioBtn.className='';
21                         }else if(_this.audioBtn.className==''){
22                                 _this.audio.pause();
23                                 _this.audioBtn.className='off';                                        
24                         }
25                 },false)
26                 
27         }
28 }
原文地址:https://www.cnblogs.com/cdwp8/p/4088446.html