Skip to main content

Javascript教程第十三章:多态与继承

Javascript教程第十三章:多态与继承

一.多态与继承

1.使用mixin来实现多继承(JS本身只允许单继承)

mixin(混合模式):将不同的功能定义为对象,直接压入需要继承的对象原型当中

2.利用原型制作选项卡(深入理解继承)

let section = document.querySelectorAll("section");

//继承方法
function extend(sub,sup){
sub.prototype = Object.create(sup.prototype);
Object.defineProperty(sub.prototype,"constructor",{
value : sub,
enumerable : false
})
}

//动画效果类
function Animation(){

}
Animation.prototype.show = function(){
this.style.display = "block";
}
Animation.prototype.changeBgc = function(col){
this.style.backgroundColor = col;
}
Animation.prototype.hide = function(){
this.style.display = 'none';
}

//选项卡类

function Tab(el){
this.tab = document.querySelector(el);
this.links = this.tab.querySelectorAll("a");
this.sections = this.tab.querySelectorAll("section");
}
extend(Tab,Animation)
Tab.prototype.run = function(){
this.bindEvent();
}
Tab.prototype.bindEvent = function(){
this.links.forEach((el,i) => {
el.addEventListener("click",() => {
this.reset()
this.action(i);
})
})
}
Tab.prototype.action = function(i){
this.changeBgc.call(this.links[i],'burlywood')
this.show.call(this.sections[i])
}
Tab.prototype.reset = function(){
this.sections.forEach((el,i) => {
this.hide.call(this.sections[i])
})
this.links.forEach((el,i) => {
this.changeBgc.call(this.links[i],'pink')
})
}

new Tab("#tab2").run()

3.优化上面TAB业务,提供更多API

function Tab(args){
args = Object.assign({
el : "null",
links : "a",
section : "section",
callback : null
},args)
this.tab = document.querySelector(args["el"]);
this.links = this.tab.querySelectorAll(args["links"]);
this.sections = this.tab.querySelectorAll(args["sections"]);
this.callback = args["callback"];
}