面向對象與閉包的使用

<html>
<head>
    <title>wirelib</title>
</head>
<script>
   //document.title = document.documentElement.clientWidth;
    /*
     *  1.onload 實例化對象
     *  2.改造函數對象的屬性及方法
     *  3.使用了定時器,事件賦值函數,需注意閉包的使用
     */
    function TabSwitch(id) {
        var _this = this;
        var oDiv = document.getElementById(id);
        this.btns = oDiv.getElementsByTagName("input");
        this.divs = oDiv.getElementsByTagName("div");
        console.log(this)
        for (var i=0; i<this.btns.length; i++) {
           this.btns[i].index = i;
           
           //事件使用對象的方法,需轉用閉包功能
           this.btns[i].onclick = function(){ _this.tab(this);}; 
        }
    }
    TabSwitch.prototype.tab = function(that){
        alert(that);    //觸發事件對象
        for (var i=0; i<this.btns.length; i++) {
           this.btns[i].className = "";
           this.divs[i].style.display="none";
        }
        that.className = "active";
        this.divs[that.index].style.display="block";
    }
    window.onload = function(){
        var tab = new TabSwitch("oDiv");
    }
</script>
<style>
    .active{border: 1px solid red;}
</style>
<body style="margin:10px; border: 10px solid red">

<div id="oDiv" style="border: 1px solid red; position: absolute; width:120px;height: 120px;"></canvas>
    <input type="button" value="a"/>
    <input type="button" value="b"/>
    <input type="button" value="c"/>
    <div>aaaa</div>
    <div style="display: none">bbbb</div>
    <div style="display: none">cccc</div>
</body>
</html>
相關文章
相關標籤/搜索