Appearance
原型模式
构造器模式中写了个People方法,但是每次实例化的时候,其中的say方法也会一起开辟空间,这导致了空间资源浪费。
为了不浪费空间,可以使用挂原型的方法添加say方法。
javascript
// 构造函数
function People(name,age){
this.name = name
this.age = age
// this.say = function(){
// console.log(this.name, this.age)
// }
}
People.prototype.say = function(){
console.log(this.name+"-", this.age)
}
var people1 = new People("Tom", 18)
people1.say()
console.log(people1)
ES6的类写法
类的写法把构造器和原型合并在了一起。
javascript
class Employee{
constructor(name,age){
this.name = name
this.age = age
}
say(){
console.log(this.name+"-"+this.age)
}
}
var employee1 = new Employee("kk", 18)
console.log(employee1)
小例子
实现标签(tab)功能,点击某个标签,内容切换到对应标签的内容
javascript
// html部分省略
class Tabs {
constructor(selector, type){
this.selector = document.querySelector(selector)
this.headerItems = this.selector.querySelectorAll(".header li")
this.boxItems = this.selector.querySelectorAll(".box li")
this.type = type
this.change()
}
change(){
for(let i = 0; i< this.headerItems.length; i++){
this.headerItems[i].addEventListener(this.type, ()=>{
for(let m=0;m<this.headerItems.length;m++){
this.headerItems[m].classList.remove("active")
this.boxItems[m].classList.remove("active")
}
this.headerItems[i].classList.add("active")
this.boxItems[i].classList.add("active")
})
}
}
}
new Tabs(".container1", "click")
new Tabs(".container2", "mouseover")