面向对象编程思想
编写代码时分析解决问题的思路
1. 求两个数最大值m,n?
1.1 定义最大值max变量
1.2 假设第一个数是最大值
max = m
1.3 让后面的数依次最大值比较,如果比最大值大,赋值给最大值
if(n > max){
max = n
}
所有数比较完后,max中存储的就是最大值
let max = Math.max(m,n)
面向过程编程思想
- 按步骤一步一步解决问题
面向对象编程思想:
找解决问题对象,调用功能解决问题, 如果对象不存在
=> 自己创建对象,封装功能,解决问题
构造函数
- 创建对象 指定对象数据类型
语法:
function Person(name,age){
// 对象属性和方法
this.name = name // this.name->给当前对象创建name属性,将形参name的值赋值给name属性
this.age = age
this.say = function(){
consolo.log('说话方法')
}
}
let p1 = new Person('jack',18)
注: 1. 构造函数名首字母大写
2. 函数体中定义属性和方法
不写其它形式代码
3. 使用new调用构造函数创建对象
对象的数据类型 => 构造函数名
let arr = new Array() // Array
原型对象
每个构造函数都有一个prototype属性指向它的原型对象
Person.prototype
选项卡面向对象编程
<script>
/*
面向对象实现选项卡效果
1. 找选项卡对象
2. 创建选项卡对象,封装其功能
构造函数: 私有属性和方法
原型对象: 公共属性和方法
*/
function Tab(id) {
this.rootEle = document.querySelector(id)
this.ulLis = this.rootEle.querySelectorAll('ul>li')
this.olLis = this.rootEle.querySelectorAll('ol>li')
}
// 切换选项和区域
Tab.prototype.onTab = function () {
let _this = this
// 1. 所有选项绑定点击事件
for (let i = 0; i < this.ulLis.length; i++) {
// 动态给选项绑定索引号
this.ulLis[i].setAttribute('index', i)
this.ulLis[i].addEventListener('click', function () {
// 清除所有选项选中效果
_this.clear()
// 给当前选项设置样式
this.className = 'active'
//获取当前选项索引号
let index = this.getAttribute('index')
_this.olLis[index].className = 'on'
})
}
}
// 清除所有选项选中效果
Tab.prototype.clear = function () {
for (let i = 0; i < this.ulLis.length; i++) {
this.ulLis[i].className = ''
this.olLis[i].className = ''
}
}
let t1 = new Tab('#tab1')
t1.onTab()
let t2 = new Tab('#tab2')
t2.onTab()
</script>