轮播图--面向对象封装
/* 函数自执行,this只想window对象 函数执行时,this指向调用该函数的对象, 例如:a.goudan(); goudan函数内部this指向a 例如:dachui(); 没有对象调用 this指向window call / apply能改变函数执行时候的this指向 事件函数,当事件触发时执行,this指向事件绑定的节点 bind能在事件函数后面追加,改变事件函数内部this指向 bind也能在定时器函数参数后面追加,改变定时器参数函数的this指向 */ function Banner($li , $btn , $tab) { //this指向实例化的对象 比如 var a = new Banner() ;a就是实例化对象 this.$li = document.querySelectorAll($li); this.$btn = document.querySelectorAll($btn); this.$tab = document.querySelectorAll($tab); this.length = this.$li.length; this.index = 0; this.init(); this.btnClick(); this.tabClick(); }; Banner.prototype.init = function () { this.$li[0].style.display = 'block'; //实例化对象 this.$tab[0].className = 'on'; //实例化对象 }; Banner.prototype.btnClick = function () { for (var i=0;i<2;i++){ // console.log(i); (function (i) { alert(i) //本来函数自执行this指向window,但是用call改变了this指向,现在指向实例化对象 this.$btn[i].onclick = function () { // console.log(i); // console.log(i); //本来事件函数this指向触发的节点,但是bind改变了this指向,现在指向实例化对象 this.change( // fn参数 function () { if(i){ // console.log(i) this.index++; this.index %= this.length; }else{ // console.log(i) this.index --; if(this.index<0)this.index=this.length-1; }} ); }.bind(this);//实例化对象 }).call(this,i); //实例化对象 console.log("i"+i) } //2 }; Banner.prototype.tabClick = function () { //this指向实例化对象 for (var i=0;i<this.length;i++){ (function (i) { this.$tab[i].onclick = function () { this.change(function () { this.index = i; }); }.bind(this); }).call(this , i); } }; Banner.prototype.change = function (fn) { //this指向实例化对象 this.$li[this.index].style.display = 'none'; this.$tab[this.index].className = ''; fn && fn.call(this);// 本来fn()自执行this指向window,但是call改变了this指向实例化对象 this.$li[this.index].style.display = 'block'; this.$tab[this.index].className = 'on'; }; function B2($li , $btn , $tab , $banner) { Banner.call(this , $li , $btn , $tab); this.$banner = document.querySelector($banner); this.timer = null; this.auto(); this.clearITV(); }; function Fn() {}; Fn.prototype = Banner.prototype; B2.prototype = new Fn(); B2.prototype.constructor = B2; B2.prototype.auto = function () { this.timer = setInterval(function () { this.change(function () { this.index ++; this.index %= this.length; }); }.bind(this),2000); }; B2.prototype.clearITV = function () { this.$banner.onmouseenter = function () { clearInterval( this.timer ); }.bind(this); this.$banner.onmouseleave = function () { this.auto(); }.bind(this); }; var b1 = new Banner('#banner .pic li' , '#banner .btn div' , '#banner .tab li'); var b2 = new B2('#banner2 .pic li' , '#banner2 .btn div', '#banner2 .tab li' , '#banner2');