js面向对象编程 tab切换案例

797 阅读1分钟

步骤

  • 自定义创建一个构造函数,把属性放在构造函数里面,将方法放在构造函数的原型对象里面(减少内存消耗)
  • 通过构造函数创建一个实例化对象,然后通过实例对象调用构造函数里面的方法 总得来说,可以就是先按照面向过程的思路解决问题,再通过面向对象实现(注意this指向)

eg1:

面向对象方式实现tab栏切换
注意在原型里面的this指向:在原型对象的最外层的this指向实例对象,如果里面存在事件(例如点击事件),要注意此时的this指向是点击事件,这里需要改变一下this的指向,fn.bind(参数1,),当然如果就只有一个点击事件,也可以通过箭头函数改变this指向,箭头函数指向的是上文中的this指向

  • html结构
    <div class="tabbox">
        <ul>
            <li class="mark">1</li>
            <li>2</li>
            <li>3</li>
        </ul>
        <ol>
            <li class="mark">1</li>
            <li>2</li>
            <li>3</li>
        </ol>
    </div>
  • css样式
        * {
            margin: 0;
            padding: 0;
        }

        .tabbox {
            width: 450px;
            height: 300px;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%)
        }

        ul,
        ol {
            list-style: none;
        }

        ul {
            width: 450px;
            height: 50px;
        }

        ul>li {
            width: 150px;
            height: 50px;
            color: white;
            font-size: 30px;
            background-color: #ccc;
            line-height: 50px;
            float: left;
            text-align: center;
        }

        ol {
            width: 450px;
            height: 250px;
        }

        ol>li {
            width: 450px;
            height: 250px;
            font-size: 80px;
            color: white;
            background-color: #666;
            text-align: center;
            line-height: 250px;
            position: absolute;
            z-index: 0;
        }

        ul>li.mark {
            background-color: tomato;
        }

        ol>li.mark {
            background-color: aqua;
            z-index: 1;
        }
  • js行为
    function Tb(selector1, selector2) {
        this.uls = document.querySelectorAll(selector1);
        this.ols = document.querySelectorAll(selector2)
    }
    Tb.prototype.move = function () {

        for (let i = 0; i < this.uls.length; i++) {
            this.uls[i].onclick = () => {
                for (let j = 0; j < this.uls.length; j++) {
                    this.uls[j].className = '';
                    this.ols[j].className = '';
                }
                this.uls[i].className = 'mark';
                this.ols[i].className = 'mark';
            }
        }
    }
    let table = new Tb("ul>li", "ol>li");
    table.move();

tab栏切换.png