🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
#用面向对象封装通用选项卡 ###改成面向对象原则: 1. 全局变量就是属性 2. 函数就是方法 3. onload中创建对象 4. 改this指向问题,在什么情况下this指向特别容易被修改(事件或者是定时器),尽量让面向对象中的this指向对象 ###复习this指向 ``` oDiv.onclick = function(){ this: oDiv // 这里的this指的是oDiv }; oDiv.onclick = show; function show() { this: oDiv // 这里的this指的还是oDiv }; oDiv.onclick = function(){ show(); }; function show() { this: window // 这里的this指的就是window } ``` ###用面向对象封装通用选项卡 ``` window.onload = function () { var t1 = new Tab(); t1.init(); }; function Tab() { this.oParent = document.getElementById('div1'); this.aInput = this.oParent.getElementsByTagName('input'); this.aDiv = this.oParent.getElementsByTagName('div'); } Tab.prototype.init = function () { var _this = this; for (var i = 0; i < this.aInput.length; i++) { this.aInput[i].index = i; this.aInput[i].onclick = function () { _this.change(this); }; } }; Tab.prototype.change = function (obj) { for (var j = 0; j < this.aInput.length; j++) { this.aInput[j].className = ''; this.aDiv[j].style.display = 'none'; } obj.className = 'active'; this.aDiv[obj.index].style.display = 'block'; }; ```